LArSoft  v10_04_05
Liquid Argon Software toolkit - https://larsoft.org/
LArUtilityHelper.h
Go to the documentation of this file.
1 
8 #ifndef LAR_UTILITY_HELPER_H
9 #define LAR_UTILITY_HELPER_H 1
10 
11 #include <algorithm>
12 #include <numeric>
13 #include <vector>
14 
15 namespace lar_content
16 {
17 
22 {
23 public:
32  template <typename T, typename Comparison>
33  static std::vector<std::size_t> GetSortIndices(const std::vector<T> &input, Comparison &compare);
34 
41  template <typename T>
42  static void SortByIndices(const std::vector<std::size_t> &order, std::vector<T> &vector);
43 };
44 
45 // ATTN templated static functions need to be defined in the header file or you get a "used by not defined" error
46 template <typename T, typename Comparison>
47 std::vector<std::size_t> LArUtilityHelper::GetSortIndices(const std::vector<T> &input, Comparison &compare)
48 {
49  std::vector<std::size_t> order(input.size());
50  std::iota(order.begin(), order.end(), 0);
51  std::sort(order.begin(), order.end(), [&](std::size_t i, std::size_t j) { return compare(input[i], input[j]); });
52 
53  return order;
54 }
55 
56 template <typename T>
57 void LArUtilityHelper::SortByIndices(const std::vector<std::size_t> &order, std::vector<T> &vector)
58 {
59  std::vector<bool> done(vector.size());
60  for (std::size_t i = 0; i < vector.size(); ++i)
61  {
62  if (done[i])
63  continue;
64  done[i] = true;
65  std::size_t idx1{i};
66  std::size_t idx2{order[i]};
67  // keep swapping indices until we move the matching index into the current index
68  while (i != idx2)
69  {
70  std::swap(vector[idx1], vector[idx2]);
71  done[idx2] = true;
72  idx1 = idx2;
73  idx2 = order[idx2];
74  }
75  }
76 }
77 
78 } // namespace lar_content
79 
80 #endif // #ifndef LAR_UTILITY_HELPER_H
auto vector(Vector const &v)
Returns a manipulator which will print the specified array.
Definition: DumpUtils.h:289
LArUtilityHelper class.
static void SortByIndices(const std::vector< std::size_t > &order, std::vector< T > &vector)
Sort a vector in place based on a supplied index ordering.
static std::vector< std::size_t > GetSortIndices(const std::vector< T > &input, Comparison &compare)
Determine the permutation that would apply to the elements of a vector if sorted in ascending order...