Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multidimensional Containers in C++

Is there any library provide a multidimensional container to use like vector<>?

I would like to see something like:

TwoD<object_class_name> D2;
ThreeD<object_class_name> D3;

and the object_class_name could be any object instead of only the builtin types.

so I can use the object like

D2[i][j]
D3[i,j,k] or D3(i,j,k)

or similar

Thanks.

like image 310
northfly Avatar asked Dec 01 '22 03:12

northfly


2 Answers

If c++11, a possible solution is using which allows aliasing of a template:

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

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

usage:

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

ThreeD<int> t3ints;
ThreeD<std::string> t3strings;
like image 168
hmjd Avatar answered Dec 24 '22 07:12

hmjd


boost::multi_array can do that.

2D array example:

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

3D array example:

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

The stored type can be a class or struct as well as a primitive type, and the memory used will be contiguous.

like image 20
rhashimoto Avatar answered Dec 24 '22 08:12

rhashimoto