Reputation: 58
In my class I'm trying to create unsigned 2d vector and then initialize it in constructor after getting its size. Here is my class:
class RobotWorld {
private:
int n;
vector <vector<int>> v;
public:
RobotWorld (int n){
n = n;
v(n, vector<int>(n, n));
for(int i = 0; i < n; ++i){
v[i][0] = i;
}
}
};
When I do it like this, I get an error: No match for call to std::vector. Could you please tell me what is wrong with my code and how I can improve it.
Upvotes: 1
Views: 1397
Reputation: 180595
You're close. When constructing a class all of the members all initialized in the member initializer list. This is where your initialization needs to be. When you do it in the constructor body, doing variable_name(stuff)
tries to call the function call operator and not the constructor. This is why you get the compiler error since vector
has no such operator. We can change the code to
RobotWorld (int n) : n(n), v(n, vector<int>(n, n)){
for(int i = 0; i < n; ++i){
v[i][0] = i;
}
}
And now both n
and v
get properly initialized and then you manipulate the vector.
Upvotes: 7