我制作了 2 个类(class),其中一个是“细胞”,另一个是“计算”。
cells 是一个二维 vector ,数据类型为“Cells”类 我想把“单元格”的对象——单元格的内容——放在一个二维 vector “单元格”中
稍后我将计算 matrixPotential 和 deltaMatrixPotential。
但我什至无法将对象放入二维 vector 中。
Cells::Cells(double matrixPotential,
double deltaMatrixPotential)
{
this->matrixPotential = matrixPotential;
this->deltaMatrixPotential = deltaMatrixPotential;
}
Calculation::Calculation()
{
std::vector<std::vector<Cells> > cells;
for(unsigned long i = 0; i < size; i++){
for(unsigned long j = 0; j < size; j++){
Cells contentOftheCell(matrixPotential,
deltaMatrixPotential);
cells[i][j] = contentOftheCell;
}
}
}
我怎样才能让它成为可能? 我可以在法 vector 中做到这一点,但在二维 vector 中似乎不可能
最佳答案
您需要分配给您的 vector ,而不仅仅是写信给它们,希望那里有可以写的东西。
std::vector<std::vector<Cells> > cells;
cells.resize(size);
for(unsigned long i = 0; i < size; i++) {
cells[i].resize(size)
for(unsigned long j = 0; j < size; j++) {
Cells contentOftheCell(matrixPotential,
deltaMatrixPotential);
cells[i][j] = contentOftheCell;
}
}
此示例通过调整大小分配内存,这比使用 vector::push_back 随时添加空间更有效。可以首先正确构建您的载体,这会好一点,但我将其作为练习留给读者。
关于c++ - 问题 : 2d Vector (nested Vector) with datatype of new class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56669658/