在C ++中使用1维数组模拟2维数组
在此问题中,我们将了解2D数组到1D数组的转换。我们将看到如何将2D数组的元素存储到1D数组。
这里,一维数组的大小与二维数组中元素的总数n*m相同。
在编程中,有两种方法可以将2D数组存储为1D数组。他们是-
行专业
专栏专业
行主行: 在行主行中,将一行的所有元素存储在一起,然后移至下一行。
如果大小为nXm的二维数组的元素的索引(i,j)存储在1-D数组中,则其在1-D数组中的索引为
(j)+(i)*m
专业栏: 在专业栏中,将列的所有元素存储在一起,然后遍历下一个列。
如果大小为nXm的二维数组的元素的索引(i,j)存储在1-D数组中,则其在1-D数组中的索引为
(i)+(j)*n
让我们看一个例子来了解这个问题,
输入: n=3,m=5,(i,j)=(0,2)
输出: row-major=
column-major=
解释:
行优先=2+0*3=3行
优先=0+2*5=10
用来说明将2D转换为1D的程序,
示例
#include<iostream>
using namespace std;
int main() {
int n = 3;
int m = 5;
int grid[n][m] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12},
{13, 14, 15}};
int i = 0;
int j = 2;
int rowMajorIndex = i*n + j;
cout<<"Index of element at index (0, 2) in 1-D array using row-major is "<<rowMajorIndex<<endl;
int colMajorIndex = i + j*m;
cout<<"Index of element at index (0, 2) in 1-D array using column-major is "<<colMajorIndex<<endl;
return 0;
}输出-
Index of element at index (0, 2) in 1-D array using row-major is 2 Index of element at index (0, 2) in 1-D array using column-major is 10