如何调整struct的2D向量

时间:2016-05-14 16:35:09

标签: c++ vector struct

我正在尝试使用C ++制作扫雷游戏,但我在调整矢量大小时遇到​​了麻烦。

这是我的所作所为: 一个向量的向量:

vector<vector<int> > mineField;

结构矢量:

struct cell{
     int value;                //(-1 mine, 0 no surrounding, # > 0 number of surrounding mines)
     int state;            //( 0 hidden, 1 revealed, 2 marked) 
     bool isMine;
};

vector<vector<cell> > mineField;

单元格的向量位于扫雷类的单独.cpp文件中。 我想要做的是重新调整单元格的向量,使其具有与整数向量相同的维度。 并将struct变量 value 初始化为int和struct结构中的值 变量 state 为0。

这是我到目前为止所尝试的:

this->mineField.resize(rowNum, vector<cell>(colNum));

    for(int i = 0; i < rowNum; i++){
        for(int j = 0; j < colNum; j++){

            this->mineField[i][j].state = 0;

            this->mineField[i][j].value = mineField[i][j];
        }
    }

当试图运行它时,我只能拥有5行×5列的尺寸(我无法弄清楚原因)。任何 其他维度退出程序,netbeans告诉我运行失败。

我也尝试过:

this->mineField.clear();
    for (int i = 0; i < rowNum; i++){

        this->mineField.push_back(vector<cell>(colNum, 0));

    }

    for(int i = 0; i < rowNum; i++){
        for(int j = 0; j < colNum; j++){

            this->mineField[i][j].state = 0;

            this->mineField[i][j].value = mineField[i][j];
        } 
    }

当试图以这种方式调整大小时,没有任何作用。

就这样:

this->mineField.resize(rowNum);

    for(int i = 0; i < rowNum; i++){

        this->mineField[i].resize(colNum);

    }

    for(int i = 0; i < rowNum; i++){
        for(int j = 0; j < colNum; j++){

            this->mineField[i][j].state = 0;

            this->mineField[i][j].value = mineField[i][j];
        } 
    }

尝试此操作可让程序运行但不适用于任何尺寸组合。

非常感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:1)

据我了解你的问题,这应该有用。

vector<vector<cell > > mineField;
vector< vector<int> > mineFeildInt;

int size=mineFeildInt.size();//get the size of the vector for vector of integers
minefield.resize(size);//resize the vector for vector of cells

for(int i=0;i<size;i++)
{
   int inner_size=mineFeildInt[i].size();//get the size of the vector of integers
   minefield[i].resize(inner_size);//resize the vector of cells
   for(int j=0;j<inner_size;j++)
   {
      minefield[i][j].state=0;
      minefield[i][j].value=mineFeildInt[i][j];//assign the integer value from the vector of integer to the value member of the structure
   }
}

答案 1 :(得分:1)

这是我的版本:

struct cell {
    int value;
    int state;
    int isMine;
};

int main()
{
    //declare source vector with sample data
    vector<vector<int>> mineFeildSource = { {10, 20, 30, 40}, {50, 60, 70}, {80, 90, 100, 110} };

    //Evaluate your destination vector
    vector<vector<cell>> mineField(mineFeildSource.size());
    for (vector<vector<int>>::size_type nSourRow = 0;
         nSourRow < mineFeildSource.size(); nSourRow++)
    {
        auto &sourRow = mineFeildSource[nSourRow];
        auto &destRow = mineField[nSourRow];

        for (vector<int>::size_type nSourCol = 0;
             nSourCol < sourRow.size(); nSourCol++)
        {
            destRow.push_back(cell{sourRow[nSourCol], 0, 0});
        }
    }

    return 0;
}