数据结构之稀疏矩阵的三元组表示(CSparseMatrix )源代码

本文介绍了使用三元组表示的稀疏矩阵数据结构,详细讲解了CSparseMatrix类的设计,并通过源代码展示了加法和乘法操作。在测试中,对稀疏矩阵的这些基本运算进行了验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CSparseMatrix.h文件

/*
*Copyright? 中国地质大学(武汉) 信息工程学院
*All right reserved.
*
*文件名称:CSparseMatrix.h
*摘       要:用三元组实现稀疏矩阵的表示及运算
*
*当前版本:1.0
*作       者:———
*完成日期:2018-04-29
*/

#pragma once
#ifndef CSPARSEMATRIX
#define CSPARSEMATRIX
#include<iostream>
using namespace std;

template<class _Ty>
struct CTrituple                              //三元组结构体定义
{
	int m_nRowIndex;                          //行下标
	int m_nColIndex;                          //列下标
	_Ty m_tData;                              //数据
};

#define MAXSIZE 55
template<class _Ty>
class CSparseMatrix {
public:
	CSparseMatrix(int size = MAXSIZE);       //构造函数
	~CSparseMatrix();                        //析构函数
	CSparseMatrix(CSparseMatrix<_Ty>& S);    //复制构造函数
	//赋值运算符
	CSparseMatrix<_Ty>& operator = (CSparseMatrix<_Ty>& S);

	void Transpose(CSparseMatrix<_Ty>& S);  //转置函数-快速转置
	// -重载加法运算符
	CSparseMatrix<_Ty> operator + (CSparseMatrix<_Ty>& S);
	// -重载乘法运算符
	CSparseMatrix<_Ty> operator * (CSparseMatrix<_Ty>& S1);

	//重载输入运算符
	friend istream& operator >>(istream& in,
		CSparseMatrix<_Ty>& S) {
		int term, row, col;
		int rindex, cindex, data;
		cout << "依次输入矩阵的行与列大小:";
		while (in >> row >> col) {
			if (row < 1 || col < 1) {
				cout << "行号或者列号个数小于1,请重新输入!" << endl;
				continue;
			}
			else {
				S.m_nRowSize = row;
				S.m_nColSize = col;
				break;
			}
		}

		cout << "输入三元组的个数:";
		while (in >> term) {
			if (term > S.m_nMaxTerm) {
				cout << "Term > m_nMaxTerm,请重新输入三元组的个数:" << endl;
				continue;
			}
			else if (term < 1) {
				cout << "Term < 1,请重新输入三元组的个数:" << endl;
				continue;
			}
			else {
				S.m_nTerm = term;
				break;
			}
		}

		cout << "依次输入三元组,格式为:行号 列号 数值" << endl;
		int count = 0;
		while (count < S.m_nTerm                                 //应先判断是否count < S.m_nTerm
			&& in >> rindex >> cindex >> data) {                 //不然会多输入一次无用的三元组
			if (rindex < 0
				|| rindex >= S.m_nRowSize
				|| cindex < 0
				|| cindex >= S.m_nColSize) {
				cout << "元素下标越界,请重新输入该三元组:" << endl;
				continue;
			}
			else {
				S.m_tmElement[count].m_nRowIndex = rindex;
				S.m_tmElement[count].m_nColIndex = cindex;
				S.m_tmElement[count].m_tData     = data;
				c
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值