简体   繁体   English

3d - > 1D数组索引

[英]3d -> 1D array indexing

in C++, what is the indexing value for a W * H * D sized 3D array? 在C ++中,W * H * D大小的3D数组的索引值是多少?

for a particular i, j, k is this the correct indexing: 对于特定的i,j,k这是正确的索引:

i*W*H+j*W+k 我* W * H + J * W + K

What you have written is equivalent to the pointer arithmetic that this would do: 你所写的内容相当于这将做的指针算术:

T x[D][H][W];

x[i][j][k];  // Pointer arithmetic done here

Obviously, depending on how you order D , H and W (or i , j , k ), the calculation will differ. 显然,根据您订购DHW (或ijk )的方式,计算会有所不同。

There is no one "correct" order, but the version you've given should work. 没有一个“正确”的订单,但您提供的版本应该有效。 The order in which you apply the indices will determine whether you do row-major or column-major indexing. 应用索引的顺序将决定您是执行行主索引还是列主索引。 If you're porting Fortran code (for example) it can make sense to reverse the "normal" C order. 如果你正在移植Fortran代码(例如),那么反转“正常”C顺序是有意义的。

Width, height and depth are meaningless in this context. 在这种情况下,宽度,高度和深度毫无意义。 What you need to know is that multidimensional arrays are stored in row-major order . 您需要知道的是,多维数组以行主顺序存储。

Yes, assuming i varies from 0 ... D-1, j varies from 0 ... H-1, and k varies from 0 ... W-1. 是的,假设i从0 ... D-1变化, j从0 ... H-1变化, k从0 ... W-1变化。

Usually, though, the purpose of having an indexer, I thought, was to express relations within a sparse matrix so you didn't need to deal with the whole thing (and expend memory for it). 通常,我认为,拥有索引器的目的是在稀疏矩阵内表达关系,这样你就不需要处理整个事情(并为它消耗内存)。 If your data span the whole matrix, you might look into creating the 3d matrix as a pointer to an array of pointers, which themselves each point to an array of pointers. 如果您的数据跨越整个矩阵,您可能会考虑将3d矩阵创建为指向指针数组的指针,指针数组本身指向一个指针数组。 Using this allows you to use the x[i][j][k] notation but may be faster. 使用此选项可以使用x[i][j][k]表示法,但可能更快。

See http://www.nr.com/cpppages/chapappsel.pdf for a description. 有关说明,请访问http://www.nr.com/cpppages/chapappsel.pdf

If you need to to iterarate over all elements it is best to do in 如果你需要迭代所有元素,最好这样做

for i
    for j
        for k

order. 订购。 This way, it would be fastest, because index of array is incremented by one each time and values could be precached. 这样,它将是最快的,因为数组的索引每次递增1并且可以预先缓存值。 There is no only one correct way to do this but you probably chose best one. 不仅有一种正确的方法可以做到这一点,但你可能选择了最好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM