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 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));
C++ Vector Library - resize() FunctionThe C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector.
Reshape the Matrix in C++ In different platform there is very useful function called 'reshape', that function is used to reshape a matrix into a new one with different size but data will be same.
vector_name. size() gives you the numbers of column in a 2D vector and vector_name[0]. size() gives you the numbers of rows in a 2D vector in C++.
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!
You have to resize the outer and inner vectors separately.
myVector.resize(n);
for (int i = 0; i < n; ++i)
myVector[i].resize(m);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With