您的位置:首页 > 理论基础 > 数据结构算法

数据结构----稀疏矩阵的快速转置

2016-03-31 16:36 483 查看
使用两种方法将稀疏矩阵快速转置
#include<iostream>
#include<vector>
using namespace std;

template<class T>
struct Triple  //三元组
{
size_t row;
size_t col;
T _value;
};

template<class T>
class SparseMatrix
{
public:
SparseMatrix(T *arr, size_t rowsize, size_t colsize,T invaild)//invaild->非特殊字
:_rowsize(rowsize),
_colsize(colsize),
_invaild(invaild)
{
for (size_t i = 0; i < _rowsize; i++)
{
for (size_t j = 0; j < _colsize; j++)
{
Triple<T> t;
if (arr[i*_colsize + j] != invaild)
{
t.row = i;
t.col = j;
t._value = arr[i*_colsize + j];
_array.push_back(t);
}
}
}
}
SparseMatrix(size_t rowsize, size_t colsize, T invaild)
:_rowsize(rowsize),
_colsize(colsize),
_invaild(invaild)
{}
SparseMatrix()
{}
SparseMatrix<T> TransposeMatrix()  //务必保持行优先
{
SparseMatrix<T> sm(_colsize, _rowsize, _invaild);
for (size_t i = 0; i < _colsize; i++)
{
size_t index = 0;
while (index < _array.size())
{
if (_array[index].col == i)
{
Triple<T> t;
t.col = _array[index].row;
t.row = _array[index].col;
t._value = _array[index]._value;
sm._array.push_back(t);
}
++index;
}
}
return sm;
}
SparseMatrix<T> FastsposeMatrix(T *array)  //快速定位转置,行优先
{
SparseMatrix<T> sm(array,_colsize,_rowsize,0);
int index = 0;
int newsize[7];
int newsign[7];
memset(newsize, 0, sizeof(newsize));
memset(newsign, 0, sizeof(newsign));
for (size_t i = 0; i < _array.size(); i++)
{
++newsize[_array[i].col];
}
for (size_t i = 1; i < _colsize; i++)
{
newsign[i] = newsign[i - 1] + newsize[i - 1];
}
for (size_t i = 0; i < _array.size(); i++)
{
int index = newsign[_array[i].col];
sm._array[index].col = _array[i].row;
sm._array[index].row = _array[i].col;
sm._array[index]._value = _array[i]._value;
newsign[_array[i].col]++;
}
return sm;
}
void Display()
{
size_t index = 0;
for (size_t i = 0; i < _rowsize; i++)
{
for (size_t j = 0; j < _colsize; j++)
{
if (_array[index].row == i&&_array[index].col == j&&index<_array.size())
{
cout << _array[index]._value;
index += 1;
}
else
{
cout << _invaild;
}
}
cout << "\n" << endl;
}
}

protected:
size_t _rowsize;
size_t _colsize;
T _invaild;
vector<Triple<T>> _array;
};

void Test1()
{
int arr[5][7] =
{
{ 0, 1, 0, 1, 0, 0, 1 },
{ 1, 0, 0, 1, 0, 0, 1 },
{ 1, 0, 0, 1, 0, 0, 1 },
{ 1, 0, 0, 1, 0, 0, 1 },
{ 1, 0, 0, 1, 0, 0, 1 },
};
SparseMatrix<int> s((int *)arr, 5, 7, 0);
SparseMatrix<int> sm1;
SparseMatrix<int> sm2;
sm1=s.TransposeMatrix();
sm2 = s.FastsposeMatrix((int*)arr);
s.Display();
sm1.Display();
sm2.Display();
}
int main()
{
Test1();
return 0;

}


本文出自 “痕迹” 博客,请务必保留此出处http://wpfbcr.blog.51cto.com/10696766/1758884
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: