How can I resize a 2D vector of objects given the width and height?

My class, GameBoard, has a member variable that is a 2D vector of an object of the class Tile. The GameBoard constructor takes width and height as parameters.

How can I get the 2D vector of Tile objects to resize according to the width and height passed to the constructor? How can I fill it with Tile objects so that I can do something like this?

myVector[i][j].getDisplayChar();

Snippet

m_vvTiles.resize(iHeight);

for(auto it = m_vvTiles.begin(); it != m_vvTiles.end(); it++ ){

    (*it).resize(iWidth,Tile(' '));
}

Solution 1:

You don't need to create external loop to resize a 2 dimensional vector (matrix). You can simply do the following one line resize() call:

//vector<vector<int>> M;
//int m = number of rows, n = number of columns;
M.resize(m, vector<int>(n));

Hope that helps!

Solution 2:

You have to resize the outer and inner vectors separately.

myVector.resize(n);
for (int i = 0; i < n; ++i)
    myVector[i].resize(m);