16

So, im trying to create a 3 dimensional 5x3x2 vector, using the vector lib and saving the number 4 in every node.

Thats what im trying:

vector<vector<vector<int> > > vec (5,vector <int>(3,vector <int>(2,4)));

for a bi dimensional 5x8 saving the int 6 in every node, this works:

vector<vector<int> > vec (5,vector <int>(8,6));
3
  • 1
    A 3D vector is something like <-1, -2, 4>. You're talking about a 3D array (simulated using a vector of vectors of vectors). A vector is a 1D array, no matter how large a number of dimensions it has.
    – Kaz
    Commented Mar 21, 2012 at 21:06
  • 3
    Please don't do this. Use boost::multi_array. Commented Mar 21, 2012 at 21:18
  • 2
    @KarlKnechtel Using Boost may not be appropriate for all people, due to licensing or build footprint constraints. Commented Aug 22, 2017 at 19:07

2 Answers 2

41

You almost got it right -- the second nested vector should be vector<vector<int> >, not just a vector<int>:

vector<vector<vector<int> > > vec (5,vector<vector<int> >(3,vector <int>(2,4)));
0
18

Also you can declare of this forms:

// first form
typedef vector<int> v1d;
typedef vector<v1d> v2d;
typedef vector<v2d> v3d;
v3d v(5, v2d(3, v1d(2, 4)));

// second form
vector<vector<vector<int> > > v = vector<vector<vector<int> > >( 5, vector<vector<int> >(3, vector<int>(2, 4)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.