1#include <iostream>
2#include <vector>
3#include <numeric> // std::iota
4#include <algorithm> // std::sort, std::stable_sort
5
6using namespace std;
7
8template <typename T>
9vector<size_t> sort_indexes(const vector<T> &v) {
10
11 // initialize original index locations
12 vector<size_t> idx(v.size());
13 iota(idx.begin(), idx.end(), 0);
14
15 // sort indexes based on comparing values in v
16 // using std::stable_sort instead of std::sort
17 // to avoid unnecessary index re-orderings
18 // when v contains elements of equal values
19 stable_sort(idx.begin(), idx.end(),
20 [&v](size_t i1, size_t i2) {return v[i1] < v[i2];});
21
22 return idx;
23}
24
25//Usage:
26for (auto i: sort_indexes(v)) {
27 cout << v[i] << endl;
28}