Preserving Original Indexes During C Sorting
Sorting data while retaining the original indexes is a common requirement in data manipulation tasks. In C , using the standard library, this task encompasses the following steps:
Implementation in C 11:
#include <iostream> #include <vector> #include <numeric> // std::iota #include <algorithm> // std::sort, std::stable_sort using namespace std; template <typename T> 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; }
Example usage:
vector<double> values = {5, 2, 1, 4, 3}; vector<size_t> sorted_indexes = sort_indexes(values); for (auto i : sorted_indexes) { cout << values[i] << endl; }
The above is the detailed content of How Can I Preserve Original Indexes When Sorting Data in C ?. For more information, please follow other related articles on the PHP Chinese website!