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?

前端 未结 4 1063
攒了一身酷
攒了一身酷 2021-01-14 01:11

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 a

4条回答
  •  有刺的猬
    2021-01-14 01:52

    Just avoid multidimensional arrays:

    template
    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 data;
    };
    
    int main()
    {
        Matrix 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).

提交回复
热议问题