简体   繁体   English

在C ++中初始化vector <vector <vector <double> >>

[英]Initialize a vector<vector<vector<double> > > in C++

I have a vector of vector of vector of doubles. 我有双向量矢量矢量。 I'm trying to initialize it. 我正在尝试初始化它。 The below code seg faults. 以下代码段错误。 Including the commented code also does not help (does not compile). 包括注释代码也没有帮助(不编译)。

vector<vector<vector<double> > > Q(MAX_GRID);
for(int row = 0; row < MAX_GRID; row++) {
    //vector<vector<double> > inQ(MAX_GRID);
    //Q[row].push_back(inQ);
    for(int col = 0; col < MAX_GRID; col++)
        for(int action = 0; action <= 3; action++)
            Q[row][col].push_back(0);
}

Change 更改

vector<vector<vector<double> > > Q(MAX_GRID);

to

vector<vector<vector<double> > > Q(MAX_GRID, vector<vector<double> >(MAX_GRID));

Otherwise the second dimension consists of empty vectors. 否则,第二维由空向量组成。

You can do the same thing with the third dimension, avoiding the loop altogether. 您可以使用第三维执行相同的操作,完全避免循环。

If you have std::array I suggest something like: 如果你有std::array我会建议:

std::array<std::array<std::array<double, 4>, MAX_GRID>, MAX_GRID> Q;

No other initialization needed. 无需其他初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM