// DataStructTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream.h>
#include <malloc.h>

void ShowArray2(int * p,int row,int col)


{
int index=0;
for(int i=0;i<row;i++)

{
for(int j=0;j<col;j++)

{
if (j==0)
cout<<p[index++];
else
cout<<" "<<p[index++];
}
cout<<endl;
}
cout<<endl;
}

void ShowArray1(int * p,int count)


{
for(int k=0;k<count;k++)

{
if (k==0)
cout<<p[k];
else
cout<<" "<<p[k];
}
cout<<endl;
}

int main(int argc, char* argv[])


{
const int N=4;
int Array2[N][N]=

{

{1,2,3,4},

{0,5,6,7},

{0,0,8,9},

{0,0,0,10},
};

int Array1[N*(1+N)/2+1];
//显示二维数组
ShowArray2(&Array2[0][0],4,4);
//将二维数组(上三角矩阵)压缩存储到一维数组中
int index=0;
for(int i=1;i<=N;i++)

{
//N-i+1为第i行应该存储的元素数
for(int j=1;j<=N-i+1;j++)

{
Array1[index++]=Array2[i-1][i+j-2]; //i+j-2=N-(N-i+1)+(j-1) //表示总阶数-本行应该存储的元素数+本行的J索引
}
}
Array1[N*(1+N)/2]=0; //在一维数组的最末元素存储三角矩阵的常数
//显示一维数组的内容
ShowArray1(Array1,sizeof(Array1)/sizeof(int));
cout<<endl<<endl;
//通过一维数组得到二维数组(上三角矩阵)
int tempArray2[N][N];
for(int j=1;j<=N;j++)

{
for(int k=1;k<=N;k++)

{
int index=0;
if (j<=k)

{
//这里必需指明:(float)(j-1),将j-1转为浮点型,否则做(j-1)/2时将被认为要(j-1)/2存到整型里,使精度降低,
//再后续的操作就是错的了.加上类型转化后,后续的操作编译器将把所有的变量以及常量提升到float后再运算.
//运算的结果是float的,所以还需要再进行一次类型转换,消除编译器警告(不转也正确,因为会自动的使float变成int).
index=(int)((float)(j-1)/2*(2*N-j+2)+k-j+1);
}
else

{
index=N*(1+N)/2+1;
}
tempArray2[j-1][k-1]=Array1[index-1];
}
}
//
ShowArray2(&tempArray2[0][0],4,4);
return 0;
}
