在由二维矩阵转为一维数组时,我们有两种方式:以列为主和以行为主。
以列为主的二维矩阵转为一维数组时,转换公式为:
index=column+row×行数
以行为主的二维矩阵转为一维数组时,转换公式为:
index=row+column×列数
#include<iostream>
#include
<iomanip>
using
namespace std;
int main()
{
int
arr1[3][4] = { { 1, 2, 3, 4 },
{
5, 6, 7, 8 },
{
9, 10, 11, 12 }
};
int
arr2[12] = { 0 };
int
row, column, index;
cout <<
"原二维资料:"
<< endl;
for
(row = 0; row < 3; row++)
{
for
(column = 0; column < 4; column++)
cout << setiosflags(ios::left)
<< setw(4)
<< arr1[row][column];
cout << endl;
}
cout <<
"以列为主:"
<< endl;
for
(row = 0; row < 3; row++)
{
for
(column = 0; column < 4; column++)
{
index
= column + row * 4;
arr2[index]
= arr1[row][column];
}
}
for
(int i = 0; i < 12; i++)
cout << setw(4)<<arr2[i]
<< " " ;
cout << endl;
cout <<
"以行为主:"
<< endl;
for
(row = 0; row < 3; row++)
{
for
(column = 0; column < 4; column++)
{
index
= row + column * 3;
arr2[index]
= arr1[row][column];
}
}
for
(int i = 0; i < 12; i++)
cout << setw(4)
<< arr2[i]
<< " ";
cout << endl;
return
0;
}