user1748601
user1748601

Reputation: 177

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);
}

Upvotes: 3

Views: 1879

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409442

If you have std::array I suggest something like:

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

No other initialization needed.

Upvotes: 2

NPE
NPE

Reputation: 500883

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.

Upvotes: 5

Related Questions