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 1066
攒了一身酷
攒了一身酷 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:43

    You can solve the problem in at least two ways, depending on your preferences. First of all - you don't need the Boost library, and you can do it yourself.

    class array{
       unsigned int dimNumber;
       vector dimSizes;
    
       float *array;
    
       array(const unsigned int dimNumber, ...){
         va_list arguments;
         va_start(arguments,dimNumber);
         this->dimNumber = dimNumber;
         unsigned int totalSize = 1;
         for(unsigned int i=0;i

    Setting an element value would be the same, you will just have to specify the new value. Of course you can use any type you want, not just float... and of course remember to delete[] the array in the destructor.

    I haven't tested the code (just wrote it straight down here from memory), so there can be some problems with calculating the position, but I'm sure you'll fix them if you encounter them. This code should give you the general idea.

    The second way would be to create a dimension class, which would store a vector which would store sub-dimensions. But that's a bit complicated and too long to write down here.

提交回复
热议问题