C++中的多维容器

nor*_*fly 3 c++ containers multidimensional-array

是否有任何库提供像vector <>一样使用的多维容器?

我希望看到类似的东西:

TwoD<object_class_name> D2;
ThreeD<object_class_name> D3;
Run Code Online (Sandbox Code Playgroud)

object_class_name可以是任何对象,而不仅仅是内置类型.

所以我可以使用像这样的对象

D2[i][j]
D3[i,j,k] or D3(i,j,k)
Run Code Online (Sandbox Code Playgroud)

或类似的

谢谢.

hmj*_*mjd 7

如果是c ++ 11,可能的解决方案是using允许别名template:

template <typename T>
using TwoD = std::vector<std::vector<T>>;

template <typename T>
using ThreeD = std::vector<std::vector<std::vector<T>>>;
Run Code Online (Sandbox Code Playgroud)

用法:

TwoD<int> t2ints;
TwoD<std::string> t2strings;

ThreeD<int> t3ints;
ThreeD<std::string> t3strings;
Run Code Online (Sandbox Code Playgroud)


rha*_*oto 5

boost::multi_array 可以做到这一点.

二维数组示例:

boost::multi_array<float, 2> float2D(boost::extents[5][10]);
float2D[0][0] = 1.0f;
Run Code Online (Sandbox Code Playgroud)

3D数组示例:

boost::multi_array<float, 3> float3D(boost::extents[5][10][20]);
float2D[0][0][0] = 1.0f;
Run Code Online (Sandbox Code Playgroud)

存储的类型可以是类或结构以及基元类型,并且使用的存储器将是连续的.