稀疏矩阵

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;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值