因为稀疏矩阵的有效元素个数较少,所以以行优先的顺序把有效元素的信息封装在一个三元组中存储在顺序表里
#include<iostream>
#include<vector>
using namespace std;
#define M 5
#define N 6
struct Tuple
{
int _row;
int _col;
int _value;
};
class SparseMatrix
{
public:
SparseMatrix(int s[M][N], int invalue) //生成矩阵的三元表
:_row(M)
, _col(N)
{
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
if (s[i][j] != invalue)
{
Tuple t;
t._row = i;
t._col = j;
t._value = s[i][j];
_array.push_back(t);
}
}
}
_dataCount = _array.size();
}
//输出矩阵
void Display()
{
int index = 0;
for (int i = 0; i < _row; i++)
{
for (int j = 0; j < _col; j++)
{
if (index<_dataCount && i == _array[index]._row
&&j == _array[index]._col)
{
cout << _array[index]._value << " ";