3
vector<bool> working_lattice(box.rect.length * box.rect.height * box.rect.width);

How do I access working_lattice[1][5][3] using the style of declaration above?

unixman83
  • 9,421
  • 10
  • 68
  • 102
  • I know it would look more like `working_lattice[? * ? * ? + ?]`. But how? – unixman83 Apr 14 '12 at 06:02
  • Ignoring, for the moment, the oddities associated with `vector`, I showed a 3D matrix that you can access using `matrix[a][b][c]` notation in an [old answer](http://stackoverflow.com/a/2216055/179910). For the moment, it passes the size as a template parameter, but it wouldn't take a huge amount to pass it as a ctor parameter instead. If I were writing it today, I'd undoubtedly use an `std::vector` instead of an actual 3D array, which would make it trivial to pass the size to the ctor. – Jerry Coffin Apr 14 '12 at 06:10
  • Three nested vectors would be stored as one contiguous block of memory as well, since each vector itself is stored in a contiguous block of memory. This would also let the machine do the multiplication work for figuring out the offset for you. – Frerich Raabe Apr 14 '12 at 06:28

3 Answers3

4

You need to access it as

(i * length * height) + (j * height) + k

So in your case

working_lattice[(i * box.rect.length * box.rect.height) + (j * box.rect.height) + k);

or

working_lattice[(1 * box.rect.length * box.rect.height) + (5 * box.rect.height) + 3);

EDIT: Since you mentioned x, y, z elsewhere

working_lattice[(x * box.rect.length * box.rect.height) + (y * box.rect.height) + z);
josephthomas
  • 3,256
  • 15
  • 20
3

This depends on whether you're using row-major or column-major ordering. Row-major is more typical in C/C++, but you can do either if you're doing it manually.

In row-major ordering, to get to the i, j, k'th element, you need to go through box.rect.height * box.rect.width * i elements to get up to the ith row, plus box.rect.width * j elements to get to the jth column of that row, plus k to get back to the kth element depthwise. To be super-explicit:

const size_t n_x = box.rect.length;
const size_t n_y = box.rect.height;
const size_t n_z = box.rect.width;
working_lattice[1 * n_x * n_z + 5 * n_z + 3]

This is obviously pretty annoying, so you might want to define an inline function or something to help out.

Danica
  • 28,423
  • 6
  • 90
  • 122
1

i.e considering this one:

A[R][S][T]

assuming that its base address is addr_base_A,

so you hope that you can get the address of one specific element A[i][j][k],

the answer I think is: S*T*i + T*j + k + addr_base_A.

Hope this helps :)

Xin
  • 113
  • 3
  • 9
  • 1
    maybe you could draw a pic to help your understanding, I figured it out by doing this. – Xin Jul 28 '18 at 14:38