C++ 使用默认值在 Struct 中实例化 2D Vector

标签 c++ c++11 vector instantiation

使用 C++11,我最初有一个具有默认值的以下形式的二维 vector :

vector<vector<int>> upper({{1,2,3,4,5,6},{7,8,9,10,11,-1},{12,13,14,15,-1,-1},{16,17,18,-1,-1,-1},{19,20,-1,-1,-1,-1},{21,-1,-1,-1,-1,-1}});
vector<vector<int>> lower({{0,0,0,0,0,0},{0,0,0,0,0,-1},{0,0,0,0,-1,-1},{0,0,0,-1,-1,-1},{0,0,-1,-1,-1,-1},{0,-1,-1,-1,-1,-1}});

这代表了我要解决的难题的上部和下部部分。现在我想修改我的程序,以便在结构内声明这些 vector ,但我不确定如何执行此操作并为二维 vector 提供默认值。这是我目前拥有的:

struct BoardState{
vector<int> row;
vector<vector<int>> upper;
vector<vector<int>> lower;

BoardState() : row(6,0), upper(6,row), lower(6,row) {};
};

但是当我尝试访问里面的内容时,它会导致段错误,使用:

#include <iostream>
#include <vector>
#include <stdlib.h>

BoardState *board;
int main(){
            using namespace std;
            ...
            for(int i=0; i<6; i++){
                for(int j=0; j<6; j++){
                    cout << board->upper[i][j] << " ";
                }
                cout << endl;
            }

}

如何为结构内的二维 vector 赋予默认值?谢谢。

最佳答案

来自 gcc warning" 'will be initialized after' :

Make sure the members appear in the initializer list in the same order as they appear in the class.

编辑:

#include <iostream>
#include <vector>
using namespace std;

struct BoardState{
vector<int> row;
vector<vector<int>> upper;
vector<vector<int>> lower;
BoardState() : row(6,0), upper(6,row), lower(6,row) {};
};

int main() {
    BoardState board;
    for(int i=0; i<6; i++){
        for(int j=0; j<6; j++){
            cout << board.upper[i][j] << " ";
        }
        cout << endl;
    }
}

关于C++ 使用默认值在 Struct 中实例化 2D Vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39538579/

相关文章:

c++ - 需要 1 个千兆 NIC 卡的精确带宽公式

c++ - 取消分配指针数组 - C++

c++ - 在二进制存档中使用Boost序列化时出错

c++ - 将 std::function<int(int)> 赋值给 std::function<const int&(const int& x)>

c++ - 通过使用(某种程度上)全局变量与静态函数变量来初始化值?

c++ - 在两个相同类的指针之间进行转换的安全性?

c++ - 在类中获取指向自身的指针

vector - Rust中的Vec <(i64,i64)>数据类型是什么?

基于字符向量重新排序数据框

c++ - 将元素插入排序 vector 并保持元素排序