NonSense - 3 months ago 17

C++ Question

How can I work with a 3 dimensional vector in C++?

`vector<vector<vector<int> > > vec (1,vector<vector<int> >(1,vector <int>(1,12)));`

When I try something like this

`cout << vec[0][0][0]; vec[0][0][1] = 13;`

everything works just fine.

The problem is that I can only change the last elements. If I try accessing the first and second element, like this

`vec[0][1][0] = 13;`

or this

`vec.push_back(vector<vector<int > >());`

vec[0].push_back(vector<int>());

v[1][0].push_back(13);

my program crashes.

How can I add and access elements in a 3d vector?

Answer

```
vector<vector<vector<int> > > vec (1,vector<vector<int> >(1,vector <int>(1,12)));
cout << vec[0][0][0]; vec[0][0][1] = 13;
```

evething is OK.

You are mistaken. Everything is *not* OK. The vector `vec[0][0]`

has only one element and thus `vec[0][0][1]`

is out of bounds and therefore the assignment has undefined behaviour. You have the same problem with `vec[0][1][0] = 13;`

and `v[1][0].push_back(13)`

You can fix that by accessing only indices that exist in your vectors. If you want more than one element, then either construct the vectors with more elements initially, or push them after construction.

At the begining I have 1x1x1 vector. So how can I push elements. using push_back() ? For example I have 1x1x1 and I want to add v[1][1][0] = 2 ?

If you for some reason want to start with 1x1x1 vector of vectors of vectors of ints and want to access `v[1][1][0]`

, here is example code to add the `v[1][1][0]`

element with minimal changes to the original vector:

```
// vector of ints that contains one element, 2
// this will vector eventually be the v[1][1] and the integer element will be v[1][1][0]
// since we initialize the integer as 2, there's no need to assign it later though
vector<int> vi(1, 2);
// vector of vectors that contains one default constructed vector
// vvi will eventually be the v[1] element and the default constructed vector will be v[1][0]
vector<vector<int>> vvi(1);
// push vi into vvi, making it vvi[1] and eventually v[1][1]
vvi.push_back(vi);
// push vvi into v, making it v[1]
v.push_back(vvi);
```