使用单个连续内存块为三维数组编制索引

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

本文关键字:数组 三维 索引 单个 连续 内存      更新时间:2023-10-16
vector<bool> working_lattice(box.rect.length * box.rect.height * box.rect.width);

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

您需要

将其访问为

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

这取决于您使用的是行主排序还是列主排序。行主在 C/C++ 中更为典型,但如果手动执行,则可以执行其中任何一个。

在行主排序中,要到达第 i、j、k 个元素,您需要遍历box.rect.height * box.rect.width * i元素才能到达第 i 行,加上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]

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

即考虑这个:

A[R][S][T]

假设其基址为 addr_base_A

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

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

希望这对:)有所帮助