使用向量的 C++ 3D 数组声明
C++ 3D array declaration using vector
我有一些 C++ 代码,我在其中使用 "vector" 和以下方法声明二维数组:
std::vector<std::vector<double>> Array2D(X, std::vector<double>Y);
其中 X 和 Y 是数组的维度。
这非常适合我需要实现的目标。
但是我想看看对 3D、XYZ 数组使用相同的方法。
我假设我开始于:
std::vector<std::vector<std::vector<double>>>
但是如何声明尺寸,即 Array3D(X, ??????)
你可以这样声明
std::vector<std::vector<std::vector<double> > > Array3D(X, std::vector<std::vector<double> >(Y, std::vector<double>(Z)));
其中 X、Y、Z 是 3D 向量的维度。
NB
最好不要使用vsoftco
提到的3D矢量
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.
有fill向量构造函数,它构造了一个有n个元素的容器,每个元素都是提供的值的副本。
std::vector<std::vector<std::vector<double>>> Array3D(X, std::vector<std::vector<double>>(Y, std::vector<double>(Z)));
将通过 Z 向量通过 Y 创建 X。您可能希望对这种类型使用 typedef
。
我有一些 C++ 代码,我在其中使用 "vector" 和以下方法声明二维数组:
std::vector<std::vector<double>> Array2D(X, std::vector<double>Y);
其中 X 和 Y 是数组的维度。
这非常适合我需要实现的目标。 但是我想看看对 3D、XYZ 数组使用相同的方法。 我假设我开始于:
std::vector<std::vector<std::vector<double>>>
但是如何声明尺寸,即 Array3D(X, ??????)
你可以这样声明
std::vector<std::vector<std::vector<double> > > Array3D(X, std::vector<std::vector<double> >(Y, std::vector<double>(Z)));
其中 X、Y、Z 是 3D 向量的维度。
NB
最好不要使用vsoftco
提到的3D矢量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.
有fill向量构造函数,它构造了一个有n个元素的容器,每个元素都是提供的值的副本。
std::vector<std::vector<std::vector<double>>> Array3D(X, std::vector<std::vector<double>>(Y, std::vector<double>(Z)));
将通过 Z 向量通过 Y 创建 X。您可能希望对这种类型使用 typedef
。