【发布时间】:2021-05-18 05:21:07
【问题描述】:
所以我有一个成员vector<vector<Foo>> _meshMatrix
如果我这样做了
_meshMatrix.resize(_numRefElementsPerRow);
for(unsigned int i = 0; i < _numRefElementsPerRow ; i++)
_meshMatrix [i].resize(_numRefElementsPerColumn);
然后我有一个Foo 对象矩阵,我可以使用 [][] 访问它的元素
for(unsigned int row = 0; row < _numRefElementsPerRow; row++)
for(unsigned int column = 0; column < _numRefElementsPerRow; column++)
_meshMatrix [row][column] = someFooObject;
为了节省内存,因为某些矩阵位置不会被填满,我想使用reserve和push_back,所以
_meshMatrix.reserve(_numRefElementsPerRow);
for(unsigned int i = 0; i < _numRefElementsPerRow ; i++)
_meshMatrix [i].reserve(_numRefElementsPerColumn);
但我不知道如何两次 push_back 进入这个矩阵
for(unsigned int row = 0; row < _numRefElementsPerRow; row++)
for(unsigned int column = 0; column < _numRefElementsPerRow; column++)
//_meshMatrix.??? = someFooObject; // how dO I use push_back here?
有什么想法吗?
【问题讨论】:
-
当
_meshMatrix的大小为零 时,您要保留的循环使用_meshMatrix [i]。调整大小和保留向量之间的内存消耗没有区别。 -
“一些矩阵位置不会被填满”——是否意味着矩阵是稀疏的?那些“零”只是在行的末尾,还是在中间?稀疏矩阵有一些特殊的格式,它们可能比一个向量更好。
-
@DanielLangr 这就像用小多边形填充在矩形内绘制的大多边形
-
@DanielLangr 这些格式是什么?
-
对了,第一个
resize调用和循环真的和单语句_meshMatrix = std::vector<std::vector<Foo>>(_numRefElementsPerRow, std::vector<Foo>(_numRefElementsPerColumn));一样