Stan  2.5.0
probability, sampling & optimization
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
sort_indices.hpp
Go to the documentation of this file.
1 #ifndef STAN__MATH__MATRIX__SORT_INDICES_HPP
2 #define STAN__MATH__MATRIX__SORT_INDICES_HPP
3 
4 
5 #include <vector>
6 #include <algorithm> // std::sort
7 #include <iostream>
8 
11 
12 namespace stan {
13 
14  namespace math {
15 
23  namespace {
24  template <bool ascending, typename C>
25  class index_comparator {
26  const C& xs_;
27  public:
34  index_comparator(const C& xs) : xs_(xs) { }
35 
44  bool operator()(int i, int j) const {
45  if (ascending)
46  return xs_[i-1] < xs_[j-1];
47  else
48  return xs_[i-1] > xs_[j-1];
49  }
50  };
51 
52 
63  template <bool ascending, typename C>
64  std::vector<int> sort_indices(const C& xs) {
65  typedef typename index_type<C>::type idx_t;
66  idx_t size = xs.size();
67  std::vector<int> idxs;
68  idxs.resize(size);
69  for (idx_t i = 0; i < size; ++i)
70  idxs[i] = i + 1;
71  index_comparator<ascending,C> comparator(xs);
72  std::sort(idxs.begin(), idxs.end(), comparator);
73  return idxs;
74  }
75 
76  }
77 
85  template <typename C>
86  std::vector<int> sort_indices_asc(const C& xs) {
87  return sort_indices<true>(xs);
88  }
89 
97  template <typename C>
98  std::vector<int> sort_indices_desc(const C& xs) {
99  return sort_indices<false>(xs);
100  }
101 
102 
103  }
104 }
105 #endif
std::vector< int > sort_indices_asc(const C &xs)
Return a sorted copy of the argument container in ascending order.
int size(const std::vector< T > &x)
Definition: size.hpp:11
std::vector< int > sort_indices_desc(const C &xs)
Return a sorted copy of the argument container in ascending order.
const C & xs_

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