class中如何使用vector作为private成员来存储和传递数据

How to use vector as a private member in class to store and pass data

假设有一个Class 解决方案:

class Solution{
private:
    int COL;
    int ROW;

    vector<vector <int>> grid(ROW, vector<int>(COL));
public:
    void setData();
};

然后把函数的定义放到setData()

void Solution::setData(){
    for (int i = 0; i < ROW; i++){
        for (int j = 0; j < COL; j++){
            grid[i][j] = 1;
        }
    }
}

衷心感谢您的任何建议!

谢谢大家,我定义了构造函数:

Solution(){
    ROW = 100;
    COL = 100;
}

但是,COL 和 ROW 在 grid(vector)

的定义中也是不可读的

谢谢!

当前您对网格的定义

vector<vector <int>> grid(ROW, vector<int>(COL));

看起来很像一个函数。说明它的类型和名称,并在别处初始化以避免这种情况:

class Solution {
private:
    const int COL;
    const int ROW;

    vector<vector <int>> grid;
public:
    void setData();

    Solution() :
        ROW{ 10 },
        COL {5 },
        grid(ROW, vector<int>(COL))
    {}
};

我制作了尺寸 const,因为它们在您的解决方案的整个生命周期内都适用,我想。

您可以更改构造函数以获取行和列的值并将它们传入,而不是使用我选择的幻数。

在您的代码中,ROW 和 COL 未定义,您尝试在函数 setData() 中使用它们。

尝试使用简单的函数添加数据

AddRow(vecotr<int> rowValue) {
     grid.push_back(rowValue);
}

如果您想使用 Set 函数,则必须检查有效性。

SetRow(uint pos, vecotr<int> rowValue){
     if (pos<=grid.size())
          return;
     ...
}

由于您可以在 运行 时填充矢量,所以让我们像这样更改 setData 函数:

class Solution{
private:
    int COL;
    int ROW;
    vector<vector <int>> grid;

public:
    void setData();

    Solution(int c, int r){
        COL = c;
        ROW = r;
    }
};

void Solution::setData(){
    vector <int> row;
    row.reserve(COL);
    for (int j = 0; j < COL; j++){
        row.push_back(1);
    }
    for (int i = 0; i < ROW; i++){
        grid.push_back(x);
    }
}

int main()
{
    Solution x(5,10);
    x.setData();
    return 0;
}

我测试了它,它工作正常。如果您不想将 1 用于网格中的所有项目,请根据需要更改第一个 for 循环,并在 setData 函数中将它们设为两个嵌套循环。