将二维数组映射到一维数组 [英] Map a 2D array onto a 1D array
问题描述
我想用一维数组表示一个二维数组.函数将传递两个索引 (x,y) 和要存储的值.这两个索引将代表一维数组的单个元素,并相应地设置它.我知道一维数组需要arrayWidth × arrayHeight的大小,但我不知道如何设置每个元素.
I want to represent a 2D array with a 1D array. A function will pass the two indicies (x,y) and the value to store. These two indicies would represent a single element of a 1D array, and set it accordingly. I know the 1D array needs to have the size of arrayWidth × arrayHeight, but I don't know how to set each element.
例如,我如何区分 (2,4,3) 和 (4,2,3)?我尝试将数组设置为 x*y,但 2*4 和 4*2 会导致数组中的相同点,我需要它们不同.
For example, how do I distinguish (2,4,3) from (4,2,3)? I tried setting the array as the x*y, but 2*4 and 4*2 would result in the same spot in the array and I need them to be different.
推荐答案
你需要决定数组元素是按行序还是列序存储,然后保持一致.http://en.wikipedia.org/wiki/Row-major_order
You need to decide whether the array elements will be stored in row order or column order and then be consistent about it. http://en.wikipedia.org/wiki/Row-major_order
C 语言对多维数组使用行序
The C language uses row order for Multidimensional arrays
为了用一维数组模拟这一点,你将行索引乘以宽度,然后加上列索引:
To simulate this with a single dimensional array, you multiply the row index by the width, and add the column index thus:
int array[width * height];
int SetElement(int row, int col, int value)
{
array[width * row + col] = value;
}
这篇关于将二维数组映射到一维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!