forpy  2
argsort.h
Go to the documentation of this file.
1 /* Author: Christoph Lassner */
2 #pragma once
3 #ifndef FORPY_UTIL_ARGSORT_H_
4 #define FORPY_UTIL_ARGSORT_H_
5 
6 #include <vector>
7 #include <random>
8 #include <type_traits>
9 #include <algorithm>
10 
11 #include "../global.h"
12 
13 namespace forpy {
23  template <typename T>
24  static std::vector<size_t> argsort(const T *v, const size_t n) {
25  // Initialize original index vector.
26  std::vector<size_t> idx(n);
27  std::iota(idx.begin(), idx.end(), 0);
28 
29  // Sort the indexes based on values in v.
30  std::sort(idx.begin(), idx.end(),
31  [&v](size_t i1, size_t i2) { return v[i1] < v[i2]; });
32 
33  return idx;
34  };
35 
44  template <typename T>
45  static std::vector<size_t> argsort(const std::vector<T> &v) {
46  return argsort(&v[0], v.size());
47  };
48 }; // namespace forpy
49 #endif // FORPY_UTIL_ARGSORT_H_
static std::vector< size_t > argsort(const T *v, const size_t n)
Highly efficient argsort realized with few STL commands.
Definition: argsort.h:24