Set a n*n square a,a any element Aij, when and only if Aij = = Aji(0 <= i <= N-1 && 0 <= J <= N-1), then matrix A is a symmetric matrix. Separated by the diagonal of the matrix, it is divided into upper and lower triangles.
Compressed storage is called a matrix storage only need to store the upper triangle/lower triangle of data, so the maximum storage N (n+1)/2 data.
symmetric matrix and compressed storage correspondence: Lower triangle storage i>=j, Symmetricmatrix[i][j] = = array[i* (i+1)/2+j]
650) this.width=650; "src="/e/u261/themes/default/images/spacer.gif "style=" Background:url ("/e/u261/lang/zh-cn/ Images/localimage.png ") no-repeat center;border:1px solid #ddd;" alt= "Spacer.gif"/>
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 in template < class t>class symmetry{public://constructor 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];//compress the symmetric matrix}}}}//print 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;}; In 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;}
Compression storage of symmetric matrices and symmetric matrices