1 /** Copyright (C) 2016 Ultimaker - Released under terms of the AGPLv3 License */
2 #ifndef UTILS_ALGORITHM_H
3 #define UTILS_ALGORITHM_H
4
5 #include <algorithm>
6 #include <vector>
7 #include <functional>
8 #include <numeric>
9
10 // extensions to algorithm.h from the standard library
11
12 namespace cura
13 {
14
15 /*!
16 * Get the order of a vector: the sorted indices of a vector
17 *
18 * {1.6, 1.8, 1.7} returns {1, 3, 2} meaning {in[1], in[3], in[2]} is a sorted
19 * vector
20 *
21 * Thanks to Lukasz Wiklendt
22 *
23 * \param in The vector for which to get the order
24 * \return An ordered vector of indices into \p in
25 */
26 template<typename T>
order(const std::vector<T> & in)27 std::vector<size_t> order(const std::vector<T> &in)
28 {
29 // initialize original index locations
30 std::vector<size_t> order(in.size());
31 std::iota(order.begin(), order.end(), 0); // fill vector with 1, 2, 3,.. etc
32
33 // sort indexes based on comparing values in v
34 std::sort(order.begin(), order.end(),
35 [&in](size_t i1, size_t i2)
36 {
37 return in[i1] < in[i2];
38 }
39 );
40
41 return order;
42 }
43
44 } // namespace cura
45
46 #endif // UTILS_ALGORITHM_H
47
48