Indexing a 3-dimensional array using a single contiguous block of memory

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

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

+3
source share
2 answers

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);
+4
source

It depends on whether you use row or column order. Row-major is more typical in C / C ++, but you can do it if you do it manually.

, i, j, k'th, box.rect.height * box.rect.width * i, i th, box.rect.width * j, j - , k, k - . -:

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]

, , , -, .

+3

All Articles