简体   繁体   English

使用向量的 C++ 3D 数组声明

[英]C++ 3D array declaration using vector

I have some C++ code where I am declaring 2D arrays using "vector" with the following method:我有一些 C++ 代码,我在其中使用“vector”和以下方法声明二维数组:

    std::vector<std::vector<double>> Array2D(X, std::vector<double>Y);

where X and Y are the dimensions of the array.其中 X 和 Y 是数组的维度。

This works beautifully for what I need to achieve.这非常适合我需要实现的目标。 However I would like to look at using the same method for 3D, XYZ arrays.但是我想看看对 3D、XYZ 数组使用相同的方法。 I assume I start with:我假设我从:

    std::vector<std::vector<std::vector<double>>>

but how do I declare the dimensions, ie Array3D(X, ?????)但是我如何声明尺寸,即 Array3D(X, ?????)

There is fill vector constructor, which constructs a container with n elements, and each element is a copy of value provided.填充向量构造函数,它构造一个包含 n 个元素的容器,每个元素都是提供的值的副本。

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.将创建 X 乘 Y 乘 Z 向量。 You probably would like to use typedef for this type.您可能希望对这种类型使用typedef

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.其中 X、Y、Z 是 3D 矢量的维度。

NB NB

It's better not to use 3D vector as mentioned by vsoftco最好不要使用vsoftco提到的 3D 矢量

DON'T use such nested vectors to create 3D matrices.不要使用这样的嵌套向量来创建 3D 矩阵。 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.最好使用平面矢量并从 3D 映射到 1D,反之亦然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM