Determine the size of the vector of the vector at the time of declaration
I recently had the opportunity to use vector<vector<vector<Some_Struct>>> threeFoldVec
, We had to do this in list
. The size threeFoldVec
is known during initialization.
I know how to determine the size of the 2_fold vector during declaration.
std::vector<std::vector<SomeStruct>> Layer_1(10, std::vector<SomeStruct>(5));
But when it comes to the 3_fold vector, I am confused.
std::vector<std::vector<std::vector<SomeStruct>>>
Layer_1(10, std::vector<std::vector<SomeStruct>>(10));
This way I can move on to the second dimension. I can obviously go through Layer_1
and use resize
or reserve
as needed, I'm interested in doing this locally, just because I find it hard-cool.
source to share
You can do it:
std::vector<std::vector<std::vector< SomeStruct >>>
Layer_1(10, std::vector<std::vector< SomeStruct >>(20, std::vector< SomeStruct >(30)));
This will create a multidimensional array 10 x 20 x 30
. Note that it is extremely inefficient to use nested vectors, it is much better to use a 1D flat vector and use a 3D addressing scheme, that is, for an array of size HEIGHT x ROWS x COLS
, you address a logical element [i][j][k]
as
[i][j][k] -> i * ROWS * COLS + j * COLS + k
This will ensure that your objects are kept contiguous, hence your access times will be better.
source to share