include“Matrix”
#pragma once
#include<iostream>
#include<vector>
using namespace std;
template<class T>
struct Triple
{
T _value;
size_t _row;
size_t _col;
};
template<class T>
class SparseMatrix
{
public:
SparseMatrix(T matrix[6][5] = NULL , size_t Row = 0, size_t Col = 0, const T& invalue = T())
:_Row(Row)
, _Col(Col)
{
for (int i = 0; i < Row; i++)
{
for (int j = 0; j < Col; j++)
{
if (matrix[i][j] != invalue)
{
Triple<T> t;
t._row = i;
t._col = j;
t._value = matrix[i][j];
v.push_back(t);
}
}
}
}
void Display()
{
int index = 0;
for (int i = 0; i < _Row; i++)
{
for (int j = 0; j < _Col; j++)
{
if (index < v.size() && v[index]._row == i && v[index]._col == j)
{
cout << v[index]._value << " ";
index++;
}
else
{
cout << "0" << " ";
}
}
cout << endl;
}
cout << endl;
}
SparseMatrix<T> Trasport()
{
SparseMatrix<T> tmp;
tmp._Row = _Col;
tmp._Col = _Row;
for (int i = 0; i < _Col; i++)
{
int index = 0;
while (index < v.size())
{
if (v[index]._col == i)
{
Triple<T> t;
t._row = v[index]._col;
t._col = v[index]._row;
t._value = v[index]._value;
tmp.v.push_back(t);
}
index++;
}
}
return tmp;
}
//快速轉置
SparseMatrix<T> FastTranspost()
{
SparseMatrix<T> tmp;
tmp._Row = _Col;
tmp._Col = _Row;
int* RowCount = new T[_Col];// 統計轉置後矩陣每一行的數據個數
int* RowStart = new T[_Col];// 統計轉置後的矩陣每行在壓縮矩陣中存儲的開始位置
memset(RowCount, 0, sizeof(int)*_Col);//初始化RowCount數組
memset(RowStart, 0, sizeof(int)*_Col);//初始化RowStart數組
// 統計轉置後矩陣每一行的數據個數 RowCounts = {2, 0, 2, 0, 2};
int index = 0;
while (index < v.size())
{
RowCount[v[index]._col]++;
index++;
}
//統計轉置後的矩陣每行在壓縮矩陣中存儲的開始位置 RowStart ={0, 2, 2, 4, 4};
RowStart[0] = 0;
for (int i = 1; i < _Col;i++)
{
RowStart[i] = RowCount[i - 1] + RowStart[i - 1];
}
// 建立轉置以後的壓縮三元組數組
index = 0;
while (index < v.size())
{
tmp.v.push_back(Triple<T>());
index++;
}
// 根據計算好每一行的起始位置進行轉置
index = 0;
while (index < v.size())
{
size_t FtpIndex = RowStart[v[index]._col]++;
tmp.v[FtpIndex]._row = v[index]._col;
tmp.v[FtpIndex]._col = v[index]._row;
tmp.v[FtpIndex]._value = v[index]._value;
index++;
}
delete[] RowCount;
delete[] RowStart;
return tmp;
}
private:
vector<Triple<T>> v;
size_t _Row;
size_t _Col;
};
main.cpp
#include"Matrix.h"
const int ROW = 6;
const int COL = 5;
void TestMatrix()
{
int matrix[ROW][COL] =
{ { 1, 0, 3, 0, 5 },
{ 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0 },
{ 1, 0, 3, 0, 5 },
{ 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0 } };
SparseMatrix<int> sm(matrix,ROW,COL,0);
sm.Display();
SparseMatrix<int> smtp = sm.Trasport();
smtp.Display();
SparseMatrix<int> smftp = sm.FastTranspost();
smftp.Display();
}
int main()
{
TestMatrix();
getchar();
return 0;
}