Bob Bob - 5 months ago 62
C++ Question

Declaring size of 3D vector

I needed to have a 2D array of vectors of myClass objects, so that I can access one of those vectors using coordinates within the array (like a 2D plane). But the size must be determined at runtime. Because of this, I decided to make it a 3D vector declared as such

vector<vector<vector <myClass> > > vex;

That way, I can just declare the size during runtime. However, I can't figure out the syntax for declaring the size of the first two outer vectors. With a single vector, it's declared like this:


But how is this done for a multi-vector like mine? Such that I can access one of the myClass vectors using


Ben Ben

If you need the vector to be filled with default constructed myClass instances you can do this:

vector<vector<vector <myClass> > > vex(size, vector<vector<myClass>>(size, vector<myClass>(size)));

Look here for more ways to initialize a std::vector.