c++ - 问题 : 2d Vector (nested Vector) with datatype of new class

标签 c++ qt vector nested

我制作了 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/

相关文章:

c++ - QObject::connect: 需要括号,信号 QSerialPort::readyRead in ..\voltage_sensor\dialop.cpp:41

c++ - 在特定 Windows 凭据中调用 API

c++ - 对右值的引用(右值的地址)

c++ - 如何在 CMake 文件中添加定义 QT_NO_DEBUG_OUTPUT?

c++ - 使 QDialog 出现在不同的屏幕中

c++ - 一个 Vector C++ 中的操作

java - 使用自定义对象对 Java Vector 进行排序和优化

r - 成对组合向量的元素

C++ - 刷新 std::cout 后没有得到结果

c++ - 理解字符引用