Stan Math Library  2.20.0
reverse mode automatic differentiation
sort_indices.hpp
Go to the documentation of this file.
1 #ifndef STAN_MATH_PRIM_MAT_FUN_SORT_INDICES_HPP
2 #define STAN_MATH_PRIM_MAT_FUN_SORT_INDICES_HPP
3 
6 #include <algorithm>
7 #include <vector>
8 
9 namespace stan {
10 namespace math {
11 
12 /*
13  * A comparator that works for any container type that has the
14  * brackets operator.
15  *
16  * @tparam ascending true if sorting in ascending order
17  * @tparam C container type
18  */
19 namespace internal {
20 template <bool ascending, typename C>
22  const C& xs_;
23 
24  public:
31  explicit index_comparator(const C& xs) : xs_(xs) {}
32 
41  bool operator()(int i, int j) const {
42  if (ascending)
43  return xs_[i - 1] < xs_[j - 1];
44  else
45  return xs_[i - 1] > xs_[j - 1];
46  }
47 };
48 
49 } // namespace internal
50 
61 template <bool ascending, typename C>
62 std::vector<int> sort_indices(const C& xs) {
63  typedef typename index_type<C>::type idx_t;
64  idx_t size = xs.size();
65  std::vector<int> idxs;
66  idxs.resize(size);
67  for (idx_t i = 0; i < size; ++i)
68  idxs[i] = i + 1;
70  std::sort(idxs.begin(), idxs.end(), comparator);
71  return idxs;
72 }
73 
74 } // namespace math
75 } // namespace stan
76 #endif
std::vector< int > sort_indices(const C &xs)
Return an integer array of indices of the specified container sorting the values in ascending or desc...
Primary template class for the metaprogram to compute the index type of a container.
Definition: index_type.hpp:18
index_comparator(const C &xs)
Construct an index comparator holding a reference to the specified container.
bool operator()(int i, int j) const
Return true if the value at the first index is sorted in front of the value at the second index; this...
int size(const std::vector< T > &x)
Return the size of the specified standard vector.
Definition: size.hpp:17

     [ Stan Home Page ] © 2011–2018, Stan Development Team.