(1) 将大小为n*n的下三角数组转换成以行为主的一维数组,且不存储内容为0的元素!
data[i][j]的位置 =i*(i+1)/2+j;
(2) 将大小为n*n的下三角数组转换成以列为主的一维数组,且不存储内容为0的元素!
data[i][j]的位置=[n+(n-j+1)]*j/2+(i-j)
(1)
#include <iostream>
#include <iomanip>
using namespace std;
int Lower[5][5]={
3,0,0,0,0,
7,5,0,0,0,
6,4,5,0,0,
8,3,2,1,0,
9,1,6,4,9
};
int main()
{
int RowMajor[15];
int Index,i,j;
cout<<"原下三角数组:\n";
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
cout<<setw(3)<<Lower[i][j];
cout<<endl;
}
//进行以行为主的数组数据转换
for(i=0;i<5;i++)
for(j=0;j<5;j++)
if(i>=j)
{
Index=i*(i+1)/2+j;
RowMajor[Index]=Lower[i][j];
}
cout<<endl;
cout<<"转换成以行为主的一维数组:\n";
for(i=0;i<15;i++)
cout<<setw(3)<<RowMajor[i];
cout<<"\n\n";
return 0;
}
(2)
#include <iostream>
#include <iomanip>
using namespace std;
int Lower[5][5]={
3,0,0,0,0,
7,5,0,0,0,
6,4,5,0,0,
8,3,2,1,0,
9,1,6,4,9
};
int main()
{
int ColMajor[15];
int Index,i,j;
cout<<"原下三角数组:\n";
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
cout<<setw(3)<<Lower[i][j];
cout<<endl;
}
//进行以列为主的数组数据转换
for(i=0;i<5;i++)
for(j=0;j<5;j++)
if(i>=j)
{
Index=(11-j)*j/2+(i-j);
ColMajor[Index]=Lower[i][j];
}
cout<<endl;
cout<<"转换成以列为主的一维数组:\n";
for(i=0;i<15;i++)
cout<<setw(3)<<ColMajor[i];
cout<<"\n\n";
return 0;
}