Stan Math Library  2.15.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 
7 #include <algorithm>
8 #include <vector>
9 
10 namespace stan {
11  namespace math {
12 
20  namespace {
21  template <bool ascending, typename C>
22  class index_comparator {
23  const C& xs_;
24 
25  public:
32  explicit index_comparator(const C& xs) : xs_(xs) { }
33 
42  bool operator()(int i, int j) const {
43  if (ascending)
44  return xs_[i-1] < xs_[j-1];
45  else
46  return xs_[i-1] > xs_[j-1];
47  }
48  };
49 
60  template <bool ascending, typename C>
61  std::vector<int> sort_indices(const C& xs) {
62  typedef typename index_type<C>::type idx_t;
63  idx_t size = xs.size();
64  std::vector<int> idxs;
65  idxs.resize(size);
66  for (idx_t i = 0; i < size; ++i)
67  idxs[i] = i + 1;
68  index_comparator<ascending, C> comparator(xs);
69  std::sort(idxs.begin(), idxs.end(), comparator);
70  return idxs;
71  }
72 
73  }
74 
75  }
76 }
77 #endif
int size(const std::vector< T > &x)
Return the size of the specified standard vector.
Definition: size.hpp:17

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