[英]How to map a 2D array in a 1D array in C++?
Lets say, I have a MxN arrays: int *b;
可以说,我有一个MxN数组: int *b;
and int **c;
和int **c;
where 哪里
b
are stored by columns (from c
) and I need to put values from c
to b
b
中的值按列存储(从c
),我需要将c
值放入b
b
are stored by rows (from c
) and I need to put values from c
to b
b
中的值按行(从c
)存储,我需要将c
值放入b
I know that basicly I would do it like that: 我知道基本上我会那样做:
j = index / N;
i = index - (j * M);
in order to convert a 1D index into a 2D co-ordinate but have a problem how to implement those 2 cases, 1) and 2)? 为了将一维索引转换为二维坐标,但是在实现这两种情况1)和2)时遇到问题?
Let W be the width of the 2D array, and H its height. 令W为2D数组的宽度,令H为其高度。 Then assuming row-major layout, the 1D index 'ix' relates to the 2D-index [x,y] as such: 然后假设行主要布局,则一维索引“ ix”与二维索引[x,y]如下所示:
ix = y*w + x;
y = ix / w; // implicit floor
x = ix % w;
eg: 例如:
const int W = 3, H=2;
int m[H][W] = {{1,2,3}, {4,5,6}};
int* oneD = &m[0][0];
assert(oneD[1*W + 2] == m[1][2]); // element 6, y=1, x=2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.