如何推送回我<Object>只有保留内存的 vector<vector>?

How do I push back to a vector<vector<Object>> in which I have only reserved memory?

本文关键字:gt vector lt 保留内存 Object 何推送      更新时间:2024-09-28

所以我有一个成员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;

相反,为了节省内存,因为一些矩阵位置不会被填满,我想使用reservepush_back,所以

_meshMatrix.reserve(_numRefElementsPerRow);
for(unsigned int i = 0; i < _numRefElementsPerRow ; i++)
_meshMatrix [i].reserve(_numRefElementsPerColumn);

但我不知道如何将两次推回这个矩阵

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 [row].push_back(value)

Fyi您正在使用_numRefElementsPerRow来迭代行和列,并为列保留空间。除非它们的大小相同,否则这是一个错误我想你是想用_numRefElementsPerColumn


EDIT:我似乎对你的代码做了一个错误的假设。我会仔细检查你的代码。第二版:我不应该在深夜这样做。键入保留->调整大小。固定的

vector<vector<Foo>> _meshMatrix;
_meshMatrix.reserve(_numRefElementsPerRow);

调用resize default将初始化vector<Foo>_numRefElementsPerRow元素。内存被分配和构造。

这里的调用预留分配足够的内存来容纳vector<Foo>_numRefElementsPerRow元素。这并不意味着已经构建了任何元素;您只需要确保行向量中有足够的空间容纳这么多。请注意,我将其称为行向量,因为您通过_numRefElementsPerrow分配它来容纳一行中的元素数量

for(unsigned int i = 0; i < _numRefElementsPerRow ; i++)
_meshMatrix [i].reserve(_numRefElementsPerColumn);

接下来,为每列保留足够的内存但是您错过了一步。这是未定义的行为。您正在对尚未构造的对象调用resize。如果您调用_meshMatrix.size(),它将返回0。要创建对象,必须构造它们,例如这是有效的:

vector<vector<Foo>> _meshMatrix;
_meshMatrix.reserve(_numRefElementsPerRow);
for(unsigned int i = 0; i < _numRefElementsPerRow ; i++) {
_meshMatrix.push_back(); // <<< construct a vector<Foo> at the end
_meshMatrix[i].reserve(_numRefElementsPerColumn);

现在,如果你想为每一列添加元素,你可以这样做:

for (unsigned j = 0; j < _numRefElementsPerColumn; j++) {
_meshMatrix[j].push_back(value); // <<< some value
}

把它放在一起:

// Create empty vector for rows
vector<vector<Foo>> _meshMatrix;
// Allocate memory ahead of time for the elements
_meshMatrix.reserve(_numRefElementsPerRow);
for(unsigned int i = 0; i < _numRefElementsPerRow ; i++) {
// Create a vector for column values
_meshMatrix.emplace_back(); // or _meshMatrix.push_back({});
// Allocate memory ahead of time for the elements
_meshMatrix[i].reserve(_numRefElementsPerColumn);
for (unsigned j = 0; j < _numRefElementsPerColumn; j++) {
// Add values
_meshMatrix[j].push_back(value); // <<< some value
}
}

您可以像这个一样进行push_back

for(unsigned int row = 0; row < _numRefElementsPerRow; row++)
{
vector<Foo> meshMatrixCols;
for(unsigned int column = 0; column < _numRefElementsPerRow; column++)
meshMatrixCols.push_back(someObject); // how dO I use push_back here?
_meshMatrix.push_back(meshMatrixCols);
}