Stan Math Library  2.14.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 <iostream>
9 #include <vector>
10 
11 namespace stan {
12  namespace math {
13 
21  namespace {
22  template <bool ascending, typename C>
23  class index_comparator {
24  const C& xs_;
25 
26  public:
33  explicit index_comparator(const C& xs) : xs_(xs) { }
34 
43  bool operator()(int i, int j) const {
44  if (ascending)
45  return xs_[i-1] < xs_[j-1];
46  else
47  return xs_[i-1] > xs_[j-1];
48  }
49  };
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;
69  index_comparator<ascending, C> comparator(xs);
70  std::sort(idxs.begin(), idxs.end(), comparator);
71  return idxs;
72  }
73 
74  }
75 
76  }
77 }
78 #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.