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?

3
  • I know it would look more like working_lattice[? * ? * ? + ?]. But how? Commented Apr 14, 2012 at 6:02
  • Ignoring, for the moment, the oddities associated with vector<bool>, I showed a 3D matrix that you can access using matrix[a][b][c] notation in an old answer. 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. Commented Apr 14, 2012 at 6: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. Commented Apr 14, 2012 at 6:28

3 Answers 3

5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Can the downvoter comment as to why? He already accepted it as the answer too
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.

Comments

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 :)

1 Comment

maybe you could draw a pic to help your understanding, I figured it out by doing this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.