您的位置:首页 > 编程语言 > C语言/C++

【C++】稀疏矩阵的普通转置与快速转置

2015-11-17 14:35 537 查看
因为稀疏矩阵的有效元素个数较少,所以以行优先的顺序把有效元素的信息封装在一个三元组中存储在顺序表里

#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]
, 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 << " ";
index++;
}
else
{
cout << "0" << " ";
}
}
cout << endl;
}
cout << endl;
}
//普通转置
SparseMatrix Transpose()
{
SparseMatrix tmp(*this);//用原矩阵初始化转置后的矩阵
swap(tmp._col, tmp._row);
int index = 0; //转置后三元表的下标
for (int i = 0; i < _col; i++)
{
int j = 0;//原三元表的下标
while (j < _dataCount)
{
if (_array[j]._col == i)
{
tmp._array[index]._col = _array[j]._row;
tmp._array[index]._row = _array[j]._col;
tmp._array[index]._value = _array[j]._value;
index++;
}
j++;
}
}
return tmp;
}

//快速转置
SparseMatrix Fast_Transpose()
{
int num[6];//存储每列非零元素的个数
int cpot[8];//存储每列第一个非零元素在转置后的三元表中的位置
SparseMatrix tmp(*this);//用原矩阵初始化转置后的矩阵
swap(tmp._col, tmp._row);
if (tmp._dataCount > 0) //三元表中至少有一个数据才进行转置
{
for (int i = 0; i < _col; i++)
{
num[i] = 0; //把每列的非零元素个数的初始值设置为0
}
for (int i = 0; i < _dataCount; i++)
{
++num[_array[i]._col]; //统计每列非零元素的个数
}
cpot[0] = 0;
for (int k = 1; k < _col; k++)
{
//每列第一个非零元素在转置后的三元表中的位置
cpot[k] = cpot[k - 1] + num[k - 1];
}
for (int i = 0; i < _dataCount; i++)
{
int col = _array[i]._col;//得到原三元表中各个值所在的列数
int p = cpot[col]; //当前列第一个非零值在新三元表中的位置
Tuple t;
t._col = _array[i]._row;
t._row = _array[i]._col;
t._value = _array[i]._value;
tmp._array[p] = t;
++cpot[col];
}
}
return tmp;
}
private:
vector<Tuple>_array;//用顺序表存储三元组
int _row;
int _col;
int _dataCount;   //顺序表中元素的个数
};
int main()
{
int s[M]
= { { 1, 0, 0, 1, 0, 9 }
, { 0, 0, 0, 0, 0 ,0}
, { 3, 0, 0, 3, 0 ,1}
, { 0, 0, 0, 0, 0 ,0}
, { 5, 0, 0, 5, 0 ,0} };
SparseMatrix sm(s, 0);
sm.Display();
SparseMatrix ct = sm.Transpose();
ct.Display();
SparseMatrix ft = ct.Fast_Transpose();
ft.Display();
cout << endl;
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: