michal
michal

Reputation: 758

3d array with negative index - c++

I need a 3 dimensional array which supports negative indices. Something similar to boost::multi_array, where I could specify bounds for each dimension, ie:

int xMin = -5; int xMax = 7;
int yMin = 3;  int yMax = 10;
int zMin = -8; int zMax = -2;
SuperArray<float> ar;
ar.setBounds(xMin, xMax, yMin, yMax, zMin, zMax);
ar[-3][5][-5] = 1.0f;

Basically, it's indexing voxel subspace in 3D :) Is there anything ready outthere, or am I to create this by myself ? thanks !

Upvotes: 0

Views: 346

Answers (2)

Jay
Jay

Reputation: 2686

Why don't you just do a translation?

Lets say the array size is:

 d1 = 100
 d2 = 100
 d3 = 100
 [d1][d2][d3]
 // where index 0 = -50 and index 99 = 50

 //Pseudo code
 // x = -1; y = 2; z = 2;
 value = array[d1/2+x][d2/2 + y][d3/2 +z];

Upvotes: 1

Barmar
Barmar

Reputation: 781058

Set the size of each dimension to Max-Min. Then when you want to access an array element, add -Min to each index. So for your dimensions, you would declare:

float ar[12][7][6];

Then to access the element you want, you do:

ar[-3-(-5)][5-3][-5-(-8)] = 1.0f;

You should be able to write a class that hides all these transformations (which is what the Boost library is doing).

Upvotes: 0

Related Questions