#include <iostream> #include <vector>template <class t>struct triple{t _ value;size_t _row;size_t _col; Triple (Const t& t =t (), size_t row = 0 ,size_t col = 0): _ Value (t), _row (Row), _col (col) {}};template <class t>class sparematrix{public: Sparematrix (t* a,size_t col,size_t row,const t invalid ): _row (Row), _col ( COL), _invalid (invalid) {for (size_t i = 0; i < row; ++i) {for (SIZE_T&NBSP;J&NBSP;=&NBSP;0;&NBSP;J&NBSP;<&NBSP;COL;&NBSP;++J) {if (invalid != a[i*col &NBSP;+&NBSP;J]) _array.push_back (triple<t> (A[i*col + j], i, j));}} Sparematrix (): _row (0), _col (0), _invalid (0) {}sparematrix<t> transport () {SpareMatrix<T > ret;for (size_t i = 0; i < _col; ++i) {Size_t index = 0;while (Index != _array.size ()) {if (_array[index]._col == i) { Triple<t> temp (_array[index]._value, _array[index]._col, _array[index]._row); ret._ Array.push_back (temp);} index++;}} Ret._col = _row;ret._row = _col;return ret;} Sparematrix<t> quicktransport () {int *rowcounts = new int [_col];int * Rowstarts = new int [_col];memset (rowcounts, 0, sizeof (int) *_col); Memset ( rowstarts, 0, sizeof (int) *_col); Sparematrix<t>ret;ret._array.resize (_array.size ());size_t index = 0;while (index < _array.size ()) {rowcounts[_array[index++]._col]++;} index = 1; rowstarts[0] = 0;while (index < _col) {Rowstarts[index] = rowcounts[index &NBSP;-&NBSP;1]&NBSP;+&NBSP;ROWSTARTS[INDEX++&NBSP;-&NBSP;1];} index = 0;while (Index < _array.size ()) {int &rowstart = rowstarts[_array[index]._col]; Triple<t>tmp (_array[index]._value, _array[index]._col, _array[index]._row); Ret._array[RowStart ++] = tmp;index++;} Ret._col = _row;ret._row = _col;ret._invalid = _invalid;return ret;} Void print () {size_t index = 0;for (size_t i = 0; i < _row; ++i) {for (size_t j = 0; j < _col; ++j) {if ( Index < _array.size () && _array[index]._col == j) {cout << _array[index++]._value << " ";} elsecout << _invalid << " ";} Cout << endl;} Cout << endl;} protected:size_t _row;size_t _col; t _invalid;std::vector<triple<t>> _array;};
This article from "Pawnsir It Road" blog, declined reprint!
Compressed storage and transpose algorithm of "code" sparse matrix