Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(' '));
}
like image 330
Habit Avatar asked Apr 08 '13 21:04

Habit


People also ask

How do you resize a 2d vector?

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));

How do I resize a vector?

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.

How do you resize a matrix in CPP?

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.

How do you find the dimensions of a 2d vector row?

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++.


2 Answers

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!

like image 143
erol yeniaras Avatar answered Oct 18 '22 20:10

erol yeniaras


You have to resize the outer and inner vectors separately.

myVector.resize(n);
for (int i = 0; i < n; ++i)
    myVector[i].resize(m);
like image 41
Mark Ransom Avatar answered Oct 18 '22 18:10

Mark Ransom