Sparsematrix.hpp
#pragma once#include<iostream>using namespace std; #include <vector>template<class T>struct Triple{ T _value; size_t _row; size_t _col;}; #define &NBSP;ROW&NBSP;6#DEFINE&NBSP;COL&NBSP;5TEMPLATE<CLASS&NBSP;T>CLASS&NBSP;SPARSEMATRIX{PUBLIC: sparsematrix (int* matrix,size_t row,size_t col,const t& invalid): _row (Row), _col (COL) { for (size_t i = 0; i < row; ++i) { for (size_t j = 0; j < col; ++j) { if (Matrix[i*col + j] != invalid) { triple<t> t; t._row = i; t._col = j; t._value = matrix[i*col + j]; _ Array.push_back (t); } } } } void display () { size_t index = 0; for (int i = 0; i < _row; ++i) { for (int j = 0; j < _col; ++j) { if (Index < _array.size () && i == _array[ Index]._row && j == _array[index]._col) { cout << _array[index]._value << " "; index++; } else cout << "0" << " "; } cout << endl; } cout << endl; } sparsematrix<t> Transposesmatrix (Int* matrix) {&nbsP; sparsematrix<t> tmp (matrix,row,col,0); tmp._row = _col; tmp ._col = _row; size_t count = 0; for (int i = 0; i < _col; ++i) { size_t index = 0; for (Index = 0; index < _array.size (); ++index) { if (_array[index]._col == i) { tmp._array[ count]._row = _array[index]._col; //transpose tmp._array[count]._col = _array[index]._ row; tmp._array[count]._value = _array[index]._value; count++; } } } tmp. Display (); return tmp; }private: vector<triple <t>> _array; size_t _row; size_t _col;}; Void test () { int matrix[row][col] = { { 1, 0, 3, 0, 5 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 1, 0, 3, 0, 5 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } }; SparseMatrix<int > SM ((int*) matrix, row, col,0); sm. Display (); sm. Transposesmatrix ((int *) matrix);}
Main.cpp
#include <iostream>using namespace std; #include "sparsematrix.hpp" int main () {test (); return 0;}
This article is from the "Molova" blog, make sure to keep this source http://molova.blog.51cto.com/10594266/1709570
C + +: Compressed storage and transpose of sparse matrices