Search code examples
c++arraysinitializer-list

How to initialize a two dimensional array using initializer_lists?


I've coded this constructor to initialize my two-dimensional array using initializer_lists.

using namespace std;

class TwoArray{
    int** array;

public:
    TwoArray(initializer_list<initializer_list<int>> list_){
        const size_t row_size = list_.size();
        const size_t column_size = list_.begin()->size();
        
        array = new int[row_size][column_size]{};
    }
};

But, this code shows this error:

main.cpp: In constructor ‘TwoArray::TwoArray(std::initializer_list<std::initializer_list<int> >)’:
main.cpp:19:48: error: array size in new-expression must be constant
         array = new int[row_size][column_size]{};
                                                ^
main.cpp:19:48: error: the value of ‘column_size’ is not usable in a constant expression
main.cpp:13:22: note: ‘column_size’ was not initialized with a constant expression
         const size_t column_size = list_.begin()->size();

And yes, I know that the length of each column may be different, but I've stripped out some code for simplicity. Actually, I am coding a mathematical matrix data structure for C++. And I also know that the two-dimensional array can be treated as one-dimensional and can be initialized easily using one-dimensional initializer_list.

How do I bypass this error? And why is this error present here?


Solution

  • You need to create one array of pointers first, then initialize them with arrays of int. Note that this may leak if any allocation throws an exception.

    array = new int*[row_size];
    for(std::size_t i = 0; i < row_size; ++i)
        array[i] = new int[column_size]{};
    

    And then analogously delete each sub-array.

    for(std::size_t i = 0; i < row_size; ++i)
        delete[] array[i];
    delete[] array;
    

    Although, unless you benefit from owning the memory directly, consider using std::vector<std::vector<int>> (or std::unique_ptr<std::unique_ptr<int[]>[]>) instead.