SparseMatrix.h
#ifndef A_H
#define A_H
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
template<class T>
struct Triple
{
int row,col;
T value;
};
const int MaxSize=100;
template<class T>
class SparseMatrix
{
public:
SparseMatrix() {};
SparseMatrix(int introws,int intcols,int interms,Triple<T> datatemp[]);
~SparseMatrix() {};
void ShowTriple();
void Trans(SparseMatrix<T> & B);
private:
Triple<T> data[MaxSize];
int rows,cols,terms;
};
#endif
SparseMatrix.cpp
#include"SparseMatrix.h"
template<class T>
SparseMatrix<T>::SparseMatrix(int introws, int intcols, int intterms, Triple<T> datatemp[])
{
rows=introws;
cols=intcols;
terms=intterms;
int i;
for(i=0;i<intterms;i++)
{
data[i]=datatemp[i];
}
}
//template<class T>
/*SparseMatrix<T>::~SparseMatrix()
{
rows=cols=terms=0;
}*/
template<class T>
void SparseMatrix<T>::ShowTriple()
{
int i,j,k,flag=0;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
flag=0;
for(k=0;k<terms;k++)
if((data[k].row==i)&&(data[k].col==j))
{
flag=1;
cout<<data[k].value<<" ";
}
if(flag==0)
//for(int h=0;h<cols;h++)
cout<<0<<" ";
//cout<<endl;
}
cout<<endl;
}
cout<<endl;
}
template<class T>
void SparseMatrix<T>::Trans(SparseMatrix<T> & B)
{
int pb,pa;
B.rows=cols;
B.cols=rows;
B.terms=terms;
if(B.terms>0)
{
pb=0;
for(int col=0;col<cols;col++)
for(pa=0;pa<terms;pa++)
if(data[pa].col==col)
{
B.data[pb].row=data[pa].col;
B.data[pb].col=data[pa].row;
B.data[pb].value=data[pa].value;
pb++;
}
}
}
Main.cpp
#include"SparseMatrix.h"
#include"SparseMatrix.cpp"
int main()
{
Triple<int> a[5]={{1,1,1},{1,2,2},{2,1,3},{2,2,4},{0,1,5}};
int i;
/*for(i=0;i<5;i++)
{
cout<<"请输入行数,列数和元素值:"<<endl;
cin>>a[i].row>>a[i].col>>a[i].value;
}*/
SparseMatrix<int> sm(3,3,5,a);
sm.ShowTriple();
SparseMatrix<int> sm1;
sm.Trans(sm1);
sm.ShowTriple();
system("pause");
return 0;
}