三元组稀疏矩阵的定义、加法、乘法——C++类、静态数组实现

本文介绍了如何使用C++通过静态数组实现稀疏矩阵类,详细阐述了三元组结构及其在矩阵加法和乘法中的应用。文章提供了测试案例及结果,并指出了可能的改进方向,如采用十字链表实现。
摘要由CSDN通过智能技术生成

稀疏矩阵

本文使用了C++封装稀疏矩阵类,静态数组存储,实现了矩阵加法与乘法。

tips

  1. 稀疏矩阵:对零元素不分配存储空间
  2. 三元组结构——行,列,值
  3. 写程序与调试建议
  • 先实现构造函数,printTriple和printMatrix函数,分别显示三元组数组,显示稀疏矩阵
  • 实现getItem函数,给定一个行、列、非零元的值,看看能否正确读取稀疏矩阵中的内容
  • 写输入函数和setItem函数,实现稀疏矩阵的插入
  • 写加法
  • 写乘法

难点

  • setItem函数,一定要记得测试三元组数组为空的时候能否正确插入,异常考虑
  • 加法和乘法要先验证能不能加(同型),能不能乘(a的列=b的行)
#include <iostream>
using namespace std;

#define MAX 100
#define ERROR 0
#define OK 1
typedef int Status;//函数结果状态类型 
typedef int DataType;

typedef struct
{
   
	int row, col;
	DataType item;
}Triple;

class TripleMatrix
{
   
private:
	Triple data[MAX];
	int mu, nu;
	DataType num;//行 列  非零元个数
public:
	TripleMatrix();
	TripleMatrix(int m, int n);//行 列
	~TripleMatrix() {
   };
	Status setItem(int row, int col, DataType item);
	int getItem(int row, int col);
	void printMatrix();
	void printTriple();
	friend void inputMatrix(int m, int n, int num, TripleMatrix &triple);
	friend bool matrixAdd(TripleMatrix &a, TripleMatrix &b);
	friend bool matrixMulity(TripleMatrix &a, TripleMatrix &b);
};

TripleMatrix::TripleMatrix()//默认构造函数
{
   
	mu = 0;
	nu = 0;
	num = 0;
}

TripleMatrix::TripleMatrix(int m, int n)
{
   
	this->mu = m;
	this->nu = n;
	this->num = 0;
}

int TripleMatrix::getItem(int row, int col)
{
   
	if (row > mu || col > nu)
		return ERROR;

	for (int i = 0; i < num; i++)
	{
   
		if (
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值