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);
i
andj
to be1
, and because in C++ vectors/arrays are 0-based, there is no index1
defined for them.vector<vector<int>> tmp(2, vector<int>({2}));
and thenvec.push_back(tmp);
. So the first one makes a 2D array of size 2x1 (so you can have a value for[1][0]
). You can combine the two lines, or even split it into three lines (make lots of 1D arrays, push them into a 2D array, and push the resulting 2D array into the 3D array).