Sparse matrices
m*n The number of valid values in the matrix far less than number of invalid values and distribution no rules .
Eg:
int array [6][5] = {{1, 0, 3, 0, 5},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{2, 0, 4, 0, 6},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0}};
Compressed storage of sparse matrices
compressed storage values store a very small number of valid data. Use {row,col,value} //column value triples Store each valid data, ternary group according to the position of the original matrix,
Program code:
#include <vector> //push pop operator[] and sequential table consistent template<class t>struct triple //defines a ternary group can be accessed directly as defined as struct{size_t _row;size_t _col; T _value; triple (Size_t row, size_t col, const t& value): _row (Row) , _col (COL), _value (value) {}}; template<class t>class sparsematrix{public : Sparsematrix (Const t* a, size_t m, size_t n,const t& invalid)// Const t& invalid indicates which is invalid data: _m (M), _n (N), invalid (invalid) {for (size_t i = 0; i < m; ++i) {for (size_t j = 0; j < n; &NBSP;++J) {if (a[i*n + j] != invalid) //not equal to invalid value {triple<t> t (i, j, &NBSP;A[I*N&NBSP;+&NBSP;J]); _a.push_back (t); }}}} void display () {Size_t index = 0;for (size_t i = 0; i < _m; ++i) {for (size_t j = 0; &NBSP;J&NBSP;<&NBSP;_N;&NBSP;++J) {if (index<_a.size () &&i == _a[index]._row && j == _a[index]._col) {cout << _a[index].value << " "; ++index;} else{cout << _invalid << " ";}} Cout << endl;} Cout << endl;} protected: //Storage Ternary Array//triple<t>* _a; Direct use of dynamic sequential table vector<triple<t>> _a;size_t _m;size_t _n; t _invalid;}; void test2 () {int a[6][5] = { { 1, 0, 3, 0, 5 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 2, 0, 4, 0 , 6 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } }; SPARSEMATRIX<INT>&NBSP;SM ((int*) a,6,5,0) //cast to a one-dimensional array array 6 row 5 column illegal value 0SM. Display (); } #include <iostream>using namespace std; #include <stdlib.h># Include "Matrix.h" int main () {//test1 (); Test2 (); System ("pause"); return 0;}
Operation Result:
1 0 3) 0 5
0 0 0) 0 0
0 0 0) 0 0
2 0 4) 0 6
0 0 0) 0 0
0 0 0) 0 0
This article is from the "10910765" blog, please be sure to keep this source http://10920765.blog.51cto.com/10910765/1783596
Compression storage of C + + sparse matrices