Learning is a mess
Learning is a mess

Reputation: 8277

C++ - ragged 4d array

I'm coding a program that would need to use a quite original (at least, new to my experience) array of ints. It should look like: my_array[a][b][c][d]

a goes from 0 to N_CORES-1, where N_CORES is the number of CPU cores on the running machine and is defined by open-mp from the beginning.

c, d takes values between 0 to ARG with ARG a line argument passed by the user

but b needs to run between 0 and a value depending on a (not the same for every core).

I tried creating this object with the new allocator with a loop:

for(int i =0;i < N_CORES; i++){
    my_array[i] = new int**[size_for_i];

but I get a segfault later on. Is it because it's not the right way to define these jagged arrays? Should I use vectors? I've never done something 4 dimensional with vectors so I'm kind of lost with it.

Edit: actually I decided to implement it another way, with an array of "only" 3d, merging the two first indexes of my previous object. Many hanks for the suggestions though!

Upvotes: 0

Views: 345

Answers (2)

R Sahu
R Sahu

Reputation: 206577

It might be easier to separate the data into various levels. Define overloaded operator [] functions at each level to provide syntactic sugar.

struct Level1Data
{
   int& operator [](int i) {return d[i];}
   int* d;
};

struct Level2Data
{
   Level1Data& operator [](int i) {return c[i];}

   Level1Data* c;
};

struct Level3Data
{
   Level2Data& operator [](int i) {return b[i];}

   Level2Data* b;
};

struct Level4Data
{
   Level3Data& operator [](int i) {return a[i];}

   Level3Data* a;
};

void foo()
{
   Level4Data myinfo;
   int k = myinfo[0][4][3][10];
};

A recursive template approach to the data, as per suggestion by presius litel snoflek.

template <int Level, typename Data>
struct MemberData
{
   MemberData<Level-1, Data>& operator [](int i) {return data[i];}
   MemberData<Level-1, Data>* data;
};

template <typename Data>
struct MemberData<0, Data>
{
   Data& operator [](int i) {return data[i];}
   Data* data;
};

void bar()
{
   MemberData<3, int> myinfo;
   int k = myinfo[0][4][3][10];
};

Upvotes: 1

JustAnotherDrone
JustAnotherDrone

Reputation: 88

try this:

int ***my_array[N_CORES];
for(int a = 0; a < N_CORES; a++)
{
    my_array[a] = new int**[size_for_a];
    for( int b = 0; b < size_for_a[a]; b++)
    {
        my_array[a][b] = new int*[ARG];
        for( int c = 0; c < ARG; c++)
        {
             my_array[a][b][c] = new int[ARG];
        }
    }
}

Upvotes: 1

Related Questions