C++

C++ implements a compressed storage instance of a sparse matrix


C++ implements compressed storage instances of sparse matrices

Sparse matrix: the matrix of M*N, the number of valid values in the matrix is much smaller than the number of invalid values, and the distribution of these data is irregular.

Compressed storage of sparse matrices: compressed stored values store very little valid data. Use {row,col,value}3 tuples to store each valid data. The 3 tuples are stored in the order of row priority according to the position in the original matrix.

Implementation code:

#include <iostream>
#include <vector>
using namespace std;

template<class T>
struct Triple    //3 tuples
{
  size_t _row;  // line
  size_t _col;  // column
  T _value;  // value

  Triple(size_t row, size_t col, const T& value)
    :_row(row)
    , _col(col)
    , _value(value)
  {}
};


template<class T>
class SparseMatrix   // Sparse matrix
{
protected:
  vector<Triple<T>> _matrix; // The compression matrix of dynamic capacity increase can be realized
  size_t _m;  // line
  size_t _n;  // column
  T _invalid;   // The default value

public:
  SparseMatrix(T* a, size_t m, size_t n, const T& invalid= T())
    :_m(m)
    , _n(n)
    , _invalid(invalid)
  {
    for (size_t i = 0; i < m; ++i)
    {
      for (size_t j = 0; j < n; ++j)
      {
        Triple<T> t(i, j, a[i*n + j]);
        _matrix.push_back(t);
      }
    }
  }

  void Display()
  {
    size_t index = 0;
    for (size_t i = 0; i < _m; ++i)
    {
      for (size_t j = 0; j < _n; ++j)
      {
        if (index < _matrix.size()
          && _matrix[index]._row== i
          &&_matrix[index]._col ==j)
        {
          cout << _matrix[index]._value << " ";
          ++index;
        }
        else
        {
          cout << _invalid << " ";
        }
      }
      cout << endl;
    }
    cout << endl;
  }



};
#include <windows.h>

void test()
{
  int a[6][5] =
  {
    { 1, 0, 2, 0, 0 },
    { 1, 0, 1, 0, 3 },
    { 2, 0, 0, 1, 2 },
    { 3, 0, 1, 0, 0 },
    { 4, 0, 2, 0, 0 },
    { 0, 3, 4, 0, 0 },
  };

  SparseMatrix<int> sm((int*)a, 6, 5, 0);
  //SymmetricMatrix(int a[][N], size_t N)
  sm.Display();

}


int main()
{
  test();

  system("pause");
  return 0;
}

Above is the sparse matrix of compressed storage of the case details, if you have any questions please leave a message or to the site community exchange discussion, thank you for reading, hope to help you, thank you for the support of the site!