稀疏矩阵
本文使用了C++封装稀疏矩阵类,静态数组存储,实现了矩阵加法与乘法。
tips
- 稀疏矩阵:对零元素不分配存储空间
- 三元组结构——行,列,值
- 写程序与调试建议
- 先实现构造函数,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 (