2

My thoughts are the following:
for e.g. a two-dimensional array:

int a[9][9];
std::vector<int** a> b;

But what if I have

/* I know, it is usually a bad practise to have more than 2 dimensional arrays, but it can happen, when you need it */
int a[3][4][5][6]; 
std::vector<int**** a> b; // ? this just looks bad
7
  • 2
    can you use std::array instead of a c-style array? Commented May 13, 2015 at 14:46
  • That's a vector of pointers, not a multi-dimensional array. Either use a vector of vectors (of vectors...), or a flat vector<int> using arithmetic for multidimensional indexing. Commented May 13, 2015 at 14:47
  • @dwcanillas yes, I could use std::array Commented May 13, 2015 at 14:47
  • @Mike Seymour using arithmetic for multidimensional indexing was downvoted by my superiors, because that would make the code hard to read and maintain. But yes, that would be a good solution. Commented May 13, 2015 at 14:49
  • 3
    @Snowman: Wrap the vector in a class, and the arithmetic in an accessor function. Then it can be as easy to read as a(1,2,3) = 42; Commented May 13, 2015 at 14:52

3 Answers 3

2

Try this:

struct MD_array{ //multidimentional array
   a[3][4][5][6];
};
std::vector<MD_array> b;

Then you can access each array like so:

b[i].a[x][y][z][w] = value;
Sign up to request clarification or add additional context in comments.

Comments

1

You could also use an alias declaration:

template <typename T, size_t I, size_t J, size_t K, size_t N>
using SomeArr = std::array<std::array<std::array<std::array<T, I>, J>, K>, N>;

int main()
{
    SomeArr<int,3,4,5,6> arr;
    std::vector<SomeArr<int,3,4,5,6>> someVec;
    someVec.push_back(arr);
}

4 Comments

You could generalize your alias quite a bit. See this question.
@Barry nice, thanks. Still on VS2012 at work so I havent learned all the stuff that comes with 2013/2015
@Barry why were structs used in that answer? Is it not possible to be done using only alias declarations?
Can you think of a way to? I'm fairly sure it's not possible.
1

You can do this

int a[3][4][5][6]; 
std::vector<int**** a> b; 

in two ways like this

int a[3][4][5][6]; 
std::vector<int ( * )[4][5][6]> b; 

b.push_back( a );

and like this

int a[3][4][5][6]; 
std::vector<int ( * )[3][4][5][6]> b; 

b.push_back( &a );

Though it is not clear what you are trying to achieve.:)

1 Comment

What Mike Seymour said in the comments, is what I'd like to achieve :) I just wanted to know, what is the best practise in this case ( I am student, and want to learn the tricks of the trade ). I am already implementing it: "Wrap the vector in a class, and the arithmetic in an accessor function. Then it can be as easy to read as a(1,2,3) = 42"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.