对称矩阵及对称矩阵的压缩存储

发布时间:2020-07-21 23:32:59 作者:清幽宁
来源:网络 阅读:404

设一个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;
}


推荐阅读:
  1. c++对称矩阵的压缩存储
  2. 对称矩阵和稀疏矩阵

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

元素

上一篇:07.guard必须用在函数

下一篇:【MongoDB学习笔记16】MongoDB的查询:find中的正则表达式

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》