对称矩阵类SymmetricMatrix
#pragma once class SymmetricMatrix { public: SymmetricMatrix(void) { size = 0; } //n为阶数,b为对称矩阵,i j从0开始算时,bij=A[i*(i+1)/2+j] i>=j int * Store_Matrix(int n,int *b) { size = (n*n+n)/2; A = new int [size]; for(int i=0;i<n;i++) for(int j=0;j<=i;j++) A[i*(i+1)/2+j] = *(b+i*n+j); return A; } int * Add__Matrix(int n,int *a,int *b) { size = (n*n+n)/2; A = new int [size]; for(int i=0;i<n;i++) for(int j=0;j<=i;j++) A[i*(i+1)/2+j] = *(b+i*n+j)+*(a+i*n+j); return A; } int getSize() { return size; } ~SymmetricMatrix(void) { } private: int * A; int size; };
测试代码
//对称矩阵 //int a[4][4] = {1,0,1,0,0,1,1,1,1,1,1,0,0,1,0,1}; //int b[4][4] = {1,5,2,6,5,2,7,9,2,7,3,8,6,9,8,4}; //SymmetricMatrix *sm = new SymmetricMatrix(); //int * A = sm->Store_Matrix(4,*b);//测试对称矩阵存储 //for(int i=0;i<sm->getSize();i++) //{ // std::cout<<A[i]<<" "; //测试对称矩阵压缩后的输出 //} std::cout<<std::endl; //A = sm->Add__Matrix(4,*b,*a);//测试对称矩阵相加 //for(int i=0;i<sm->getSize();i++) //{ // std::cout<<A[i]<<" "; //测试对称矩阵相加后的输出 //} std::cout<<std::endl;