Sorting with Index Tracking in C
Sorting data while preserving original indexes is a common task in data analysis and manipulation. In C , achieving this requires some thoughtful programming techniques.
To sort a sequence of samples in ascending order while tracking their original indexes, one can utilize lambda expressions and the standard library. The sort_indexes function below demonstrates this approach:
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 values in v using std::stable_sort to maintain original order for equal values stable_sort(idx.begin(), idx.end(), [&v](size_t i1, size_t i2) { return v[i1] < v[i2]; }); return idx; }
This function returns an index vector that can be used in subsequent iterations:
for (auto i : sort_indexes(v)) { cout << v[i] << endl; }
Customizations can be made to provide a sort function, comparator, or automatic reordering of the original vector within the sort_indexes function.
The above is the detailed content of How Can I Sort Data in C While Tracking Original Indices?. For more information, please follow other related articles on the PHP Chinese website!