Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Errors nesting vectors<> within vectors<>

I'm having a problem nesting vectors 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?

like image 975
dymk Avatar asked Dec 16 '22 14:12

dymk


1 Answers

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.

like image 62
Benjamin Lindley Avatar answered Dec 25 '22 22:12

Benjamin Lindley