Is it possible in c++ for a class to have a member which is a multidimensional array whose dimensions and extents are not known until runtime?

c++, c++11, multidimensional-array

Solution

Just avoid multidimensional arrays:

template<typename T>
class Matrix
{
    public:
    Matrix(unsigned m, unsigned n)
    :   n(n), data(m * n)
    {}

    T& operator ()(unsigned i, unsigned j)  {
        return data[ i * n + j ];
    }

    private:
    unsigned n;
    std::vector<T> data;
};

int main()
{
    Matrix<int> m(3, 5);
    m(0, 0) = 0;
    // ...
    return 0;
}

A 3D access (in a proper 3D matrix) would be:

T& operator ()(unsigned i, unsigned j, unsigned k)  { 
    // Please optimize this (See @Alexandre C) 
    return data[ i*m*n + j*n + k ]; 
}

Getting arbitrary dimensions and extent would follow the scheme and add overloads (and dimensional/extent information) and/or take advantage of variadic templates.

Having a lot of dimensions you may avoid above (even in C++11) and replace the arguments by a std::vector. Eg: T& operator(std::vector indices). Each dimension (besides the last) would have an extend stored in a vector n (as the first dimension in the 2D example above).

Problem

I originally asked using nested std::array to create an multidimensional array without knowing dimensions or extents until runtime but this had The XY Problem of trying to accomplish it with std::array. The questions One-line initialiser for Boost.MultiArray and How do I make a multidimensional array of undetermined size a member of a class in c++? and their answers give some helpful information how to use Boost::MultiArray to avoid needing to know the extents of the dimensions at runtime, but fail to demonstrate how to have a class member that can store an array (created at runtime) whose dimensions and extents are not known until runtime.

Original source

Related problems