c 2b 2b sorting and keeping track of indexes

Solutions on MaxInterview for c 2b 2b sorting and keeping track of indexes by the best coders in the world

showing results for - "c 2b 2b sorting and keeping track of indexes"
Emma
16 Jul 2019
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}