使用单个连续的内存块索引3维数组

问题描述 投票:3回答:3
vector<bool> working_lattice(box.rect.length * box.rect.height * box.rect.width);

如何使用上述声明的方式访问working_lattice[1][5][3]

c++ multidimensional-array arrayaccess integer-arithmetic
3个回答
4
投票

您需要以其身份访问它

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

所以在你的情况下

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

要么

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

编辑:因为你在其他地方提到过x,y,z

working_lattice[(x * box.rect.length * box.rect.height) + (y * box.rect.height) + z);

3
投票

这取决于您是使用行主要还是列主要排序。 Row-major在C / C ++中更为典型,但如果您手动执行,则可以执行任一操作。

在行主要排序中,要获得i,j,k'元素,你需要通过box.rect.height * box.rect.width * i元素来达到ith行,加上box.rect.width * j元素到达该行的jth列,加上k到深入地回到kth元素。要超级明确:

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]

这显然很烦人,所以你可能想要定义一个内联函数或者其他东西来帮助你。


1
投票

即考虑这个:

A[R][S][T]

假设它的基地址是addr_base_A

所以你希望你能得到一个特定元素A[i][j][k]的地址,

我认为答案是:S*T*i + T*j + k + addr_base_A

希望这可以帮助 :)

© www.soinside.com 2019 - 2024. All rights reserved.