There are 3 problems with your code:
- You are not declaring a member variable with initialization:
std::vector<int> row(V);
int foo(double);
See how those two look the same. Both define a member function. Except in your case the compiler then fails to find a type definition for V
and complains that V
is not a type.
You have to use {}
to initialize member variables inside classes:
class Foo {
int x{5};
};
- You are using the wrong type in the initialization of the vector, which causes a problem for the matrix:
#include<iostream>
#include<vector>
class graph {
private:
int V;
std::vector<int> row{V};
std::vector<std::vector<int>> matrix{V,row};
public:
graph(int v): V(v) {}
};
<source>:8:42: error: non-constant-expression cannot be narrowed from type 'int' to 'std::vector::size_type' (aka 'unsigned long') in initializer list [-Wc++11-narrowing]
std::vector<std::vector<int>> matrix{V,row};
^
<source>:8:42: note: insert an explicit cast to silence this issue
std::vector<std::vector<int>> matrix{V,row};
^
static_cast<size_type>( )
- You are getting the wrong constructor for the row vector.
If you change V
to std::size_t
, as it should be, you get another error:
<source>:7:26: error: non-constant-expression cannot be narrowed from type 'std::size_t' (aka 'unsigned long') to 'int' in initializer list [-Wc++11-narrowing]
std::vector<int> row{V};
^
<source>:7:26: note: insert an explicit cast to silence this issue
std::vector<int> row{V};
^
static_cast<int>( )
The problem is that std::vector<int> row{V};
is like std::vector<int> row{1, 2, 3, 4};
, making a vector containing the int
V
as element. It does not create a vector of size V
. You have to call the constructor for std::vector(std::size_t)
explicitly.
So overall this gives you:
#include<iostream>
#include<vector>
class graph {
private:
std::size_t V;
std::vector<int> row{std::vector<int>(V)};
std::vector<std::vector<int>> matrix{V,row};
public:
graph(std::size_t v): V(v) {}
};
graph g(5);
https://godbolt.org/z/qrobf9cGq