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(' '));
}
You have to resize the outer and inner vectors separately.
myVector.resize(n);
for (int i = 0; i < n; ++i)
myVector[i].resize(m);
You don`t need a loop to resize a 2 dimensional vector (matrix). You can simply do the following one line resize() call:
//vector<vector<int>> M;
//int n = number of rows, m = number of columns;
M.resize(n, vector<int>(m));
Hope that helps!
We can also use single line code:
matrix.resize( row_count , vector<int>( column_count , initialization_value ) );
If code is repeatedly changing the dimensions and matrix is sometimes shrinking also then before re-sizing clear the old state of matrix(2D vector)
matrix.clear();
matrix.resize( row_count , vector<int>( column_count , initialization_value ) );
// we can create a 2D integer vector with 3 rows and 5 columns having "-1" as initial value by:
matrix.clear();
matrix.resize(3, vector<int> (5,-1));