Dead
Dead

Reputation: 3

C++ Multidimensional array

I have a 3D array

double values[30][30][30];

I have a loop where I assign values to the array; Something like:

for(int z = 0;z<30; z++)
   for (int y = 0;y<30; y++)
      for (int x = 0;x<30; x++)
        values[z][y][x] = intensity;
end

So this is how I am filling the array. The problem is that I want to create column in addition to intensity to store another variable. For instance, the second to last line should be something like

values[z][y][x] = intensity | distance;

I hope you get the idea. My knowledge is limited and I couldn't come up with a solution. Thanks for your suggestions.

Upvotes: 0

Views: 185

Answers (1)

Mario
Mario

Reputation: 36567

This is really dependant on your datatypes. The easiest solution is using a struct:

struct data {
    float intensity; // or replace 'float' with whatever datatype you need
    float distance;
};

Use this struct instead of the datatype you're using now for the array, then later on set the values:

values[z][y][x].intensity = intensity;
values[z][y][x].distance = distance;

If you're using small values only (e.g. char for each value only) you could as well use bitwise operators to store everything in an integer:

values[z][y][x] = intensity << 8 | distance;
intensity = values[z][y][x] >> 8;
distance = values[z][y][x] & 255;

But I wouldn't advise you to do so unless you're really savy with that value ranges (e.g. for saving bitmap/texture stuff).

Upvotes: 4

Related Questions