Sort value and return its index using C++

Created at 2018-11-18 Updated at 2018-11-18 Category C++ Tag C++

Input a vector and returns index after sorting using C++

1
2
3
4
5
6
7
8
9
10
11
12
template <typename T>
vector<T> sortIndexes(const vector<T> &v, bool ascend) {
// initialize original index locations
IntList idx(v.size());
iota(idx.begin(), idx.end(), 0);
// sort indexes based on comparing values in v
sort(idx.begin(), idx.end(), [&v, ascend](size_t i1, size_t i2) {return ascend ? v[i1] < v[i2] : v[i1] > v[i2];});
return idx;
}

Table of Content

Site by GoingMyWay using Hexo & Random

I am a ML and RL research student

Hide