Thứ Hai, 5 tháng 2, 2018

C++ Algorithm 101: get index of sort algorithm

Hi,
Do you wonder to ask how to get index of a sorted array in C++. The answer is not straightforward, but tangible with C++11 lambda. Keep it in your C++ toolbox, you might need it quite often. I hope people will include some ways to do it easily in C++ next version.

template <typename T>
vector<int> sort_indexes(const vector<T> &v) {

  // initialize original index locations
  vector<int> idx(v.size());
  iota(idx.begin(), idx.end(), 0);

  // sort indexes based on comparing values in v
  sort(idx.begin(), idx.end(),
       [&v](size_t i1, size_t i2) {return v[i1] < v[i2];});

  return idx;
}
See you in the next post. Happy 2018 with productivity.