koho.cpp  1.1.0
utilities.h
Go to the documentation of this file.
1 
7 // Author: AI Werkstatt (TM)
8 // (C) Copyright 2019, AI Werkstatt (TM) www.aiwerkstatt.com. All rights reserved.
9 
10 #ifndef KOHO_UTILITIES_H
11 #define KOHO_UTILITIES_H
12 
13 #include <string>
14 #include <vector>
15 #include <utility> // pair
16 #include <algorithm> // sort
17 
18 using namespace std;
19 
20 namespace koho {
21 
22  // Provide the index of the maximum in an array.
23 
24  template <class X>
25  unsigned long maxIndex(X* x,
26  unsigned long n) {
27 
28  unsigned long max_index = 0;
29  X max_value = x[max_index];
30 
31  for (unsigned long i=1; i<n; ++i) {
32  if (max_value < x[i]) {
33  max_index = i;
34  max_value = x[max_index];
35  }
36  }
37 
38  return max_index;
39  }
40 
41  // Sort 2 vectors by the first vector.
42 
43  template <class X, class S>
44  void sort2VectorsByFirstVector(std::vector<X>& x, std::vector<S>& s,
45  long start, long end,
46  bool increase=true) {
47 
48  // Combine vector x and vector s into vector pair<x,s>
49  std::vector<std::pair<X, S>> pxs(x.size());
50  auto x_itr = x.begin();
51  auto s_itr = s.begin();
52  for (auto &p : pxs) {
53  p.first = *(x_itr++);
54  p.second = *(s_itr++);
55  }
56 
57  // Sort vector pair<x,s> by x
58  if (increase) {
59  sort(pxs.begin()+start, pxs.end()-(pxs.size()-end),
60  [](const std::pair<X, S> &a, const std::pair<X, S> &b) -> bool { return a.first < b.first; });
61  } else { // decrease
62  sort(pxs.begin()+start, pxs.end()-(pxs.size()-end),
63  [](const std::pair<X, S> &a, const std::pair<X, S> &b) -> bool { return a.first > b.first; });
64  }
65 
66  // Copy sorted vector pair<x,s> back into vector x and vector s
67  x_itr = x.begin();
68  s_itr = s.begin();
69  for (auto& p : pxs) {
70  *(x_itr++) = p.first;
71  *(s_itr++) = p.second;
72  }
73  }
74 
75 } // namespace koho
76 
77 #endif
Definition: decision_forest.cpp:20
STL namespace.
unsigned long maxIndex(X *x, unsigned long n)
Definition: utilities.h:25
void sort2VectorsByFirstVector(std::vector< X > &x, std::vector< S > &s, long start, long end, bool increase=true)
Definition: utilities.h:44