Home >Backend Development >C++ >How Can I Sort a Vector in C While Preserving Original Indices?
Sorting with Index Preservation in C
In the realm of data manipulation, sorting is a fundamental operation that arranges elements into a desired order. While sorting algorithms inherently preserve the order of equal elements, it may be desirable to track the original indexes of the sorted elements to maintain their original context.
One approach to this problem is to use lambda functions in C 11. A lambda is an anonymous function that can capture variables from its surrounding scope. This allows for concise and flexible sorting operations that can access external data.
Here's a customized sort_indexes function that combines lambdas with the standard library's stable_sort algorithm:
#include <vector> #include <algorithm> using namespace std; template <typename T> vector<size_t> sort_indexes(const vector<T> &v) { // Initialize original indexes vector<size_t> idx(v.size()); iota(idx.begin(), idx.end(), 0); // Sort indexes based on values in v stable_sort(idx.begin(), idx.end(), [&](size_t i1, size_t i2) { return v[i1] < v[i2]; }); return idx; }
In this function, we first initialize a vector idx with the original indexes of the input vector v. Then, we use stable_sort to sort the indexes based on a lambda comparator that compares the values in v. The use of stable_sort ensures that elements with equal values maintain their original order within the sorted result.
To use this function, simply pass the vector of elements as an argument and it will return a vector of sorted indexes. For example, given a vector [5, 2, 1, 4, 3], the returned vector idx would be [1, 2, 4, 3, 0].
This technique enables you to sort elements while preserving their original indexes, providing flexibility in subsequent data processing tasks.
The above is the detailed content of How Can I Sort a Vector in C While Preserving Original Indices?. For more information, please follow other related articles on the PHP Chinese website!