Home > Backend Development > C++ > How Can I Sort Data in C While Tracking Original Indices?

How Can I Sort Data in C While Tracking Original Indices?

Barbara Streisand
Release: 2025-01-03 12:54:40
Original
167 people have browsed it

How Can I Sort Data in C   While Tracking Original Indices?

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;
}
Copy after login

This function returns an index vector that can be used in subsequent iterations:

for (auto i : sort_indexes(v)) {
  cout << v[i] << endl;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template