Search code examples
c++variable-length-array

Allocation for multidimension array, partially of variable length, in C++


Let's say I have a multidimension array, which in C99 I could write like this:

#define SIZE1 10
int size2;

[...]

int myArray[SIZE1][size2];

Although supported by several compilers, this is not strictly C++, and won't be included until C++14. To obtain the same (apart stack/heap problem irrelevant for my case) using boost::scoped_array, I write:

boost::scoped_array<int> myArray[SIZE1];
for (int i = 0; i < SIZE1; i++)
    myArray[i].reset(new int[size2]);

So, not so concise expression. Am I missing something, or for multidimension arrays with variable length there is no easy plain C++ way to obtain a quick allocation?

Some reference: Why aren't variable-length arrays part of the C++ standard?


Solution

  • std::vector will take both a size and an initial value, which you can use to set initial size of both the outer and inner vector:

    vector< vector<int> > myArray(SIZE1, vector<int>(size2));
    

    boost::multi_array is specifically designed as a multidimensional array, and is more fitting than boost::scoped_array.

    boost::multi_array<int, 2> myArray(boost::extents[SIZE1][size2])