Learner_51
Learner_51

Reputation: 1075

C++ 5 dimensional vector?

I am trying to make a 5 dimensional vector and I can’t seem to get it to work. I know if I need to write a 3 dimensional vector, I could write it in the following way: vector< vector< vector<string> > > block(27, vector< vector<string> > (27, vector<string>(27)));

Then I call it: block[x][y][z] = “hello”;

I wrote the 5 dimensional vector in the following way and it gives me error. vector< vector< vector< vector< vector<string> > > > > block(27, vector< vector< vector< vector<string> > > >(27, vector< vector< vector<string> > >(27, vector< vector<string> >(27, vector<string>(27)))));

Can you please tell me how to write a 5 dimensional vector in the right way? Thanks a lot.

Upvotes: 3

Views: 1242

Answers (3)

carlsborg
carlsborg

Reputation: 2939

Consider using the Boost Multidimensional Array Library for higher dimensional arrays.

http://www.boost.org/doc/libs/1_43_0/libs/multi_array/doc/user.html

"Boost MultiArray is a more efficient and convenient way to express N-dimensional arrays than existing alternatives (especially the std::vector> formulation of N-dimensional arrays). The arrays provided by the library may be accessed using the familiar syntax of native C++ arrays. Additional features, such as resizing, reshaping, and creating views are available (and described below)."

Upvotes: 6

Marco
Marco

Reputation: 1346

But you should stop and think if a dictionary would work better. If the data is sparse you'll save a ton of memory. Create a key using the 5 dimensions, and create only the members you need.

Upvotes: 3

Loki Astari
Loki Astari

Reputation: 264639

The final vector in your 5 dimensional array does not have a type that it is an array of.

vector< vector< vector< vector< vector > > > > 
                                     ^^
                                     Here. What is the base vector a vector off?

To make things easy to read a couple of typedefs would be nice:

typedef std::vector<std::string>     Dim1;
typedef std::vector<Dim1>            Dim2;
typedef std::vector<Dim2>            Dim3;
typedef std::vector<Dim3>            Dim4;
typedef std::vector<Dim4>            Dim5;

Dim5 block(27, Dim4(27, Dim3(27, Dim2(27, Dim1(27)))));

Upvotes: 6

Related Questions