如何在构造函数中编辑 2D 矢量

How can I edit a 2D vector in a Constructor

本文关键字:编辑 2D 矢量 构造函数      更新时间:2023-10-16

感谢您的所有帮助,我已经将初始化移至构造函数,但是,我在定义 2D 向量时遇到困难:

这是我所做的:

private:
        vector < vector <int> > Matrix;
        vector < vector <int> > temp_m;
        vector <int> elements
        string input;
        int value;
function()
{
//Initialize Both Matrices (one which holds the puzzle and the
//other which holds the values between 1 and 9
//Create a vector of vectors:
for(int i = 0; i < 9; i++)
    elements.push_back(i+1);
for(int i = 0; i < 9; i++)
    Matrix[i].push_back(elements);  //ERROR HERE
}

我在定义 2D 矩阵的行中遇到错误。我想将矩阵推回其索引,因为它是矩阵的矩阵。

"row"的声明和它的构造不在同一个地方。构造属于初始值设定项列表:

class MyClass
{
public:
    MyClass::MyClass()
      : row(9,0), elements(9)
    {
    }
private:
        vector < vector <int> > Matrix;
        vector < vector <int> > temp_m;
        vector <int> row;
        vector <int> elements;
        string input;
        int value;
}

如果您有任何其他特殊的成员变量大小调整或初始化,则需要构造参数(例如上面的矩阵和temp_e),它们也属于初始值设定项列表。

这是不合法的(无论如何,肯定是在 C++11 之前,C++11 中有变化,但我不确定确切的规则)。您可以改为在构造函数初始值设定项列表中指定它:

A::A() : row(9, 0), elements(9) {}

并更改为:

private:
    vector<int> row;
    vector<int> elements;

尝试从声明中删除(9 , 0)。在 C++ 中,不能从类变量声明调用构造函数。您需要使用初始值设定项列表从类构造函数执行此操作。