设一个N*N的方阵A,A中任意元素Aij,当且仅当Aij == Aji(0 <= i <= N-1 && 0 <= j <= N-1),则矩阵A是对称矩阵。以矩阵的对角线为分隔,分为上三角和下三角。
压缩存储称矩阵存储时只需要存储上三角/下三角的数据,所以最多存储n(n+1)/2个数据。
对称矩阵和压缩存储的对应关系:下三角存储i>=j, SymmetricMatrix[i][j] == Array[i*(i+1)/2+j]
0 1 2 3 4
1 0 1 2 3
2 1 0 1 2
3 2 1 0 1
4 3 2 1 0
Symmetry.h中
template < class T>
class Symmetry
{
public:
//构造函数
Symmetry(T* arr, size_t size)
:_arr(new T[size*(size+1)/2])
, _size(size*(size + 1)/2)
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (i >= j)
{
_arr[i*(i + 1) / 2 + j] = arr[i*size + j];//把对称矩阵压缩
}
}
}
}
//打印
void Print(size_t size)
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
int row = i;
int col = j;
if (row < col)
{
swap(row, col);
}
cout << _arr[row*(row+ 1) / 2 + col] << " ";
}
cout << endl;
}
cout << endl;
}
protected:
T *_arr;
size_t _size;
};
test.cpp中
#include <iostream>
using namespace std;
#include "Symmetry.h"
void Test()
{
int arr[5][5] = {
{0,1,2,3,4},
{1,0,1,2,3},
{2,1,0,1,2},
{3,2,1,0,1},
{4,3,2,1,0}
};
Symmetry<int>s((int*)arr, 5);
s.Print(5);
}
int main()
{
Test();
system("pause");
return 0;
}
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。