
#include using namespace std; template //三元组 struct Trituple { int row; int col; T val; }; //稀疏矩阵声明 template class SparseMatrix { public: SparseMatrix(int maxt=100); ~SparseMatrix(); bool TransposeTo(SparseMatrix &); bool AddTo(const SparseMatrix&); bool TransposeTo_Faster(SparseMatrix&); void Input(); void Output(); private: Trituple int rows,cols,terms; int maxterms; }; template SparseMatrix { maxterms=maxt; data=new Trituple terms=rows=cols=0; } template SparseMatrix { if (data!=NULL) { delete[] data; } } //普通转置 template bool SparseMatrix { if (terms>B.maxterms) { return false; } B.rows=cols; B.cols=rows; B.terms=terms; if (terms>0) { int p=0; for (int j=1;j<=cols;j++) { for (int k=0;k if (data[k].col==j) { B.data[p].row=j; B.data[p].col=data[k].row; B.data[p].val=data[k].val; p++; } } } } return true; } //快速转置 template bool SparseMatrix { if (terms>B.maxterms) { return false; } B.rows=cols; B.cols=rows; B.terms=terms; if (terms>0) { int *num,*cpot; num=new int[cols]; cpot=new int[cols]; for (int j=0;j num[j]=0; } for (int k=0;k num[data[k].col-1]++; } //求出B中每一行的起始下标cpot[] cpot[0]=0; for (int j=1;j cpot[j]=cpot[j-1]+num[j-1]; } //执行转置操作 for (int p,k=0;k p=cpot[data[k].col-1]++; B.data[p].row=data[k].col; B.data[p].col=data[k].row; B.data[p].val=data[k].val; } delete[] num; delete[] cpot; } return true; } template void SparseMatrix { cout<<"intput the matrix' row:"; int row1; cin>>row1; cout<<"intput the matrix' col:"; int col1; cin>>col1; cout<<"input "< rows=row1; cols=col1; for (int i=0;i for (int j=0;j cin>>number; if (number!=0) { data[terms].row=i+1; data[terms].col=j+1; data[terms].val=number; terms++; } } } } template void SparseMatrix { T **tempArray=new T*[rows]; for (int i1=0;i1 tempArray[i1]=new int[cols]; } for (int j=0;j for (int k=0;k tempArray[j][k]=0; } } for (int i=0;i tempArray[data[i].row-1][data[i].col-1]=data[i].val; } for (int j=0;j for (int k=0;k cout< cout< for (int l=0;l delete[] tempArray[l]; } delete tempArray; cout< template bool SparseMatrix { if (rows!=B.rows||cols!=B.cols) { return false; } bool flag=false; int tempTerms=terms; for (int i=0;i flag=false; for (int j=0;j if (data[j].col==B.data[i].col&&data[j].row==B.data[i].row) { data[j].val+=B.data[i].val; flag=true; } } if (flag==false) { data[++terms-1].col=B.data[i].col; //数组下标操作注意事项 data[terms-1].row=B.data[i].row; data[terms-1].val=B.data[i].val; } } return true; } int main() { cout<<"此程序演示稀疏矩阵的普通转置和快速转置操作"< SparseMatrix SparseMatrix sm.Input(); cout<<"sm is"< sm.TransposeTo(sm1); cout<<"Transposition of sm is "< sm.TransposeTo_Faster(sm2); cout<<"Transposition of sm is "< SparseMatrix cout<<"input a new matrix"< cout<<"sm3 is"< if(sm.AddTo(sm3)) { cout<<"after adding sm3 ,sm is"< } else cout<<"the two matrix can't add"< return 0; }
