问题
I have some C++ code where I am declaring 2D arrays using "vector" with the following method:
std::vector<std::vector<double>> Array2D(X, std::vector<double>Y);
where X and Y are the dimensions of the array.
This works beautifully for what I need to achieve. However I would like to look at using the same method for 3D, XYZ arrays. I assume I start with:
std::vector<std::vector<std::vector<double>>>
but how do I declare the dimensions, ie Array3D(X, ?????)
回答1:
There is fill vector constructor, which constructs a container with n elements, and each element is a copy of value provided.
std::vector<std::vector<std::vector<double>>> Array3D(X, std::vector<std::vector<double>>(Y, std::vector<double>(Z)));
will create X by Y by Z vector. You probably would like to use typedef
for this type.
回答2:
You can declare like
std::vector<std::vector<std::vector<double> > > Array3D(X, std::vector<std::vector<double> >(Y, std::vector<double>(Z)));
Where X, Y, Z are the dimension of 3D vector.
NB
It's better not to use 3D vector as mentioned by vsoftco
DON'T use such nested vectors to create 3D matrices. They are slow, since the memory is not guaranteed to be contiguous anymore and you'll get cache misses. Better use a flat vector and map from 3D to 1D and viceversa.
来源:https://stackoverflow.com/questions/33028073/c-3d-array-declaration-using-vector