summaryrefslogtreecommitdiff
path: root/include/gudhi_laplacian/sparse_vector.hpp
blob: 58dd40ce4ad35ad8d51f733ad46b844ad34119c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#pragma once

#include <vector>
#include <algorithm>
#include <utility>
#include <type_traits>

namespace Gudhi_laplacian
{
  template <typename T>
  using Sparse_vector = std::vector<std::pair<unsigned int, T> >;

  template <typename T>
  void compress_sparse_vector(Sparse_vector<T> & row)
  {
    static_assert(std::is_arithmetic<T>::value, "Only arithmetic types are supported.");
    
    Sparse_vector<T> tmp(row); 
    row.clear();
    std::sort(tmp.begin(), tmp.end());
    for (auto it = tmp.cbegin(); it != tmp.cend(); ++it)
    {
      if (row.empty())
      {
        if (it->second != T())
        {
          row.push_back(*it);
        }
      }
      else if (it->first == row.back().first)
      {
        T x = row.back().second + it->second;
        if (x == T())
        {
          row.pop_back();
        }
        else
        {
          row.back().second = x;
        }
      }
      else if (it->second != T())
      {
        row.push_back(*it); 
      }
    }
  }
}