C++ 给定宽度和高度,如何调整对象的 2D 矢量大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15889578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I resize a 2D vector of objects given the width and height?
提问by Habit
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.
我的类GameBoard
有一个成员变量,它是类的对象的二维向量Tile
。所述GameBoard
构造函数采用的宽度和高度作为参数。
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?
如何Tile
根据传递给构造函数的宽度和高度调整对象的二维向量?我怎样才能用Tile
对象填充它以便我可以做这样的事情?
myVector[i][j].getDisplayChar();
Snippet
片段
m_vvTiles.resize(iHeight);
for(auto it = m_vvTiles.begin(); it != m_vvTiles.end(); it++ ){
(*it).resize(iWidth,Tile(' '));
}
回答by Mark Ransom
You have to resize the outer and inner vectors separately.
您必须分别调整外部和内部向量的大小。
myVector.resize(n);
for (int i = 0; i < n; ++i)
myVector[i].resize(m);
回答by erol yeniaras
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:
您不需要创建外部循环来调整二维向量(矩阵)的大小。您可以简单地执行以下一行resize()
调用:
//vector<vector<int>> M;
//int m = number of rows, n = number of columns;
M.resize(m, vector<int>(n));
Hope that helps!
希望有帮助!
回答by ravi_kumar_yadav
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));