|
| 1 | +#include <algorithm> // std::sort, std::stable_sort |
| 2 | +#include <iostream> |
| 3 | +#include <numeric> // std::iota |
| 4 | +#include <vector> |
| 5 | + |
| 6 | +using namespace std; |
| 7 | + |
| 8 | +// https://stackoverflow.com/questions/1577475/c-sorting-and-keeping-track-of-indexes |
| 9 | + |
| 10 | +template <typename T> |
| 11 | +vector<size_t> sort_indexes(const vector<T>& v) { |
| 12 | + // initialize original index locations |
| 13 | + vector<size_t> idx(v.size()); |
| 14 | + iota(idx.begin(), idx.end(), 0); |
| 15 | + |
| 16 | + // sort indexes based on comparing values in v |
| 17 | + // using std::stable_sort instead of std::sort |
| 18 | + // to avoid unnecessary index re-orderings |
| 19 | + // when v contains elements of equal values |
| 20 | + stable_sort(idx.begin(), idx.end(), |
| 21 | + [&v](size_t i1, size_t i2) { return v[i1] < v[i2]; }); |
| 22 | + |
| 23 | + return idx; |
| 24 | +} |
| 25 | + |
| 26 | +int main() { |
| 27 | + vector<int> v = { 4, 6, 7, 1, 3, 2, 9, 8, 7, 0, 5 }; |
| 28 | + for(auto i : sort_indexes(v)) { |
| 29 | + cout << i << "th element: " << v[i] << endl; |
| 30 | + } |
| 31 | + return 0; |
| 32 | +} |
| 33 | + |
| 34 | +/* |
| 35 | +9th element: 0 |
| 36 | +3th element: 1 |
| 37 | +5th element: 2 |
| 38 | +4th element: 3 |
| 39 | +0th element: 4 |
| 40 | +10th element: 5 |
| 41 | +1th element: 6 |
| 42 | +2th element: 7 |
| 43 | +8th element: 7 |
| 44 | +7th element: 8 |
| 45 | +6th element: 9 |
| 46 | +*/ |
0 commit comments