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 ROW 6 #define COL 5 template<class T> class 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){ 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; }
本文出自 “moLova” 博客,请务必保留此出处http://molova.blog.51cto.com/10594266/1709570
原文地址:http://molova.blog.51cto.com/10594266/1709570