Errors nesting vectors<> within vectors<>
I'm having a problem nesting vectors 开发者_JAVA技巧within vectors, the equivalent of a 2D array in C. I have tried the code demonstrating this posted on numerous website, to no avail.
class Board
{
public:
vector< vector<Cell> > boardVect; //Decalre the parent vector as a memebr of the Board class
Board()
{
boardVect(3, vector<Cell>(3)); //Populate the vector with 3 sets of cell vectors, which contain 3 cells each, effectivly creating a 3x3 grid.
}
};
When I attempt to compile, I receive this error:
F:\main.cpp|52|error: no match for call to '(std::vector >) (int, std::vector)'
Line 52 is: boardVect(3, vector<Cell>(3));
Is the error that I am getting an error when constructing the parent vector with the 3 vector classes?
You need to use the initialization list in order to call constructors on the members of your class, i.e.:
Board()
:boardVect(3, vector<Cell>(3))
{}
Once you've entered the body of the constructor, it's too late, all the members are already constructed, and you can only call non-constructor member functions. You could of course do this:
Board()
{
boardVect = vector<vector<Cell> >(3, vector<Cell>(3));
}
But the initialization list is preferred.
精彩评论