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 1069
攒了一身酷
攒了一身酷 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:46

    Instead of a multidimensional array you could use a 1D-array with an equal amount of indices. I could not test this code, but I hope it will work or give you an idea of how to solve your problem. You should remember that arrays, which do not have a constant length from the time of being compiled, should be allocated via malloc() or your code might not run on other computers. (Maybe you should create a class array for the code below)

    #include 
    
    int* IndexOffset; //Array which contains how many indices need to be skipped per  dimension
    int  DimAmount;   //Amount of dimensions
    int  SizeOfArray = 1; //Amount of indices of the array
    
    void AllocateArray(int* output,         //pointer to the array which will be allocated
                       int* dimLengths,     //Amount of indices for each dimension: {1D, 2D, 3D,..., nD}
                       int dimCount){       //Length of the array above
    
    DimAmount = dimCount;
    int* IndexOffset = (int*) malloc(sizeof(int) * dimCount);
    int temp = 1;
    
    for(int i = 0; i < dimCount; i++){
    
    temp = temp * dimLengths[i];
    IndexOffset[i] = temp; 
    
    }
    
    
    for(int i = 0; i < dimCount; i++){
    
    SizeOfArray = SizeOfArray * dimLengths[i];
    
    }
    
    output = (int*)malloc(sizeof(int) * SizeOfArray);
    
    }
    

    To get an index use this:

    int getArrayIndex(int* coordinates //Coordinates of the wished index as an array (like dimLengths)
                ){
    
    int index;
    int temp = coordinates[0];
    
    for(int i = 1; i < DimAmount; i++){
    
         temp = temp + IndexOffset[i-1] * coordinates[i];
    
    }
    index = temp;
    return index;
    }
    

    Remember to free() your array as soon as you do not need it anymore:

    for(int i = 0; i < SizeOfArray; i++){
    
        free(output[i]);
    
    }
    free(output);
    

提交回复
热议问题