Geno3D
A simple 3D visualisation library, using C++/SFML.
 All Classes Functions Variables
vecsort.hpp
1 #include <vector>
2 #include <algorithm>
3 #include <numeric>
4 
5 namespace vecsort {
6 
7  template <typename T, typename Compare>
8  void getSortPermutation(
9  std::vector<unsigned>& out,
10  const std::vector<T>& v,
11  Compare compare = std::less<T>())
12  {
13  out.resize(v.size());
14  std::iota(out.begin(), out.end(), 0);
15 
16  std::sort(out.begin(), out.end(),
17  [&](unsigned i, unsigned j){ return compare(v[i], v[j]); });
18  }
19 
20  template <typename T>
21  void applyPermutation(
22  const std::vector<unsigned>& order,
23  std::vector<T>& t)
24  {
25  assert(order.size() == t.size());
26  std::vector<T> st(t.size());
27  for(unsigned i=0; i<t.size(); i++)
28  {
29  st[i] = t[order[i]];
30  }
31  t = st;
32  }
33 
34  template <typename T, typename... S>
35  void applyPermutation(
36  const std::vector<unsigned>& order,
37  std::vector<T>& t,
38  std::vector<S>&... s)
39  {
40  applyPermutation(order, t);
41  applyPermutation(order, s...);
42  }
43 
44  template<typename T, typename Compare, typename... SS>
45  void sortVectors(
46  const std::vector<T>& t,
47  Compare comp,
48  std::vector<SS>&... ss)
49  {
50  std::vector<unsigned> order;
51  getSortPermutation(order, t, comp);
52  applyPermutation(order, ss...);
53  }
54 
55  // make less verbose for the usual ascending order
56  template<typename T, typename... SS>
57  void sortVectorsAscending(
58  const std::vector<T>& t,
59  std::vector<SS>&... ss)
60  {
61  sortVectors(t, std::less<T>(), ss...);
62  }
63 
64 }