Allocation of a multidimensional array, partially variable length, in C ++

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

#define SIZE1 10
int size2;

[...]

int myArray[SIZE1][size2];

Although supported by several compilers, it is not strictly C ++ and will not be included until C ++ 14. To get the same (separate stack / heap issue that does not matter for my case) with 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 multidimensional matrices with variable lengths there is no simple simple C ++ - a way to get quick selection?

Some link: Why are variable-length arrays not part of the C ++ standard?

+3
source share
4 answers

std::vector , , , :

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

boost::multi_array , boost::scoped_array.

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

++, , 'row_index * rowlength + column_index'.

0

, , . , :

template <class T>
class Matrix
{
public:
    Matrix(const unsigned int _width,const unsigned int _height)
        :width(_width)
        ,height(_height)
    {
        elements.resize(width * height);//one allocation !
    }
    //x goes on width
    //y on height
    T&              get(const unsigned int x,const unsigned int y)
    {
        return elements[y * width + x];
    }
public:
    unsigned int    width;
    unsigned int    height;
    std::vector<T>  elements;
};

//usage:
Matrix<int> m(width_size,height_size);
m.get(10,10) = element;

, x y y * width + x .

, . , .

0

If you need a multidimensional array, you can use pointers; resizing will require copying to a new one and deleting the old one, but you can do the following:

int** m;
int rows, cols;
cin >> rows >> cols;
m = new int* [rows];
for (int i = 0; i < rows; i++) {
    m[i] = new int [cols];
}

for (int i = 0; i < rows; i++) {
    delete [] m[i];
}
delete [] m;   

or alternatively you can use a pointer to a 1D array, for example:

int* m;
int rows, cols;
cin >> rows >> cols;
m = new int [rows*cols];

and access it:

for (int i = 0; i < rows; i++)
    for (int j = 0; j < cols; j++)
        m[i*cols+j] = i;

containing the delete statement:

delete [] m;   
0
source

All Articles