Last active
December 4, 2024 09:29
-
-
Save ucasfl/083c14921c063ef0a3a31972274cfd9a to your computer and use it in GitHub Desktop.
sort index by array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <iostream> | |
#include <numeric> | |
#include <vector> | |
using namespace std; | |
template <typename T> | |
std::vector<size_t> sort_indexes(const vector<T> & v) | |
{ | |
// initialize original index locations | |
vector<size_t> idx(v.size()); | |
iota(idx.begin(), idx.end(), 0); | |
// sort indexes based on comparing values in v | |
// using std::stable_sort instead of std::sort | |
// to avoid unnecessary index re-orderings | |
// when v contains elements of equal values | |
stable_sort(idx.begin(), idx.end(), [&v](size_t i1, size_t i2) { return v[i1] < v[i2]; }); | |
return idx; | |
} | |
int main() | |
{ | |
std::vector<int> vec1{9, 5, 7, 4}; | |
auto vec = sort_indexes(vec1); | |
// output 3 1 2 0 | |
for (auto i : vec) | |
{ | |
std::cout << i << std::endl; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment