c++multidimensional-arrayarrayaccessinteger-arithmetic

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 style of declaration above?


Solution

  • 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);