C++ 3D array declaration using vector

拈花ヽ惹草 提交于 2020-07-23 02:02:48

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!