C++ std::stable_sort
std::stable_sort sorts a range in place and keeps equivalent elements in their original relative order.
A simple example
std::stable_sort
- Start with A with rank 2, B with rank 1, C with rank 2
- Do this Stable sort by rank
- Result B, A, C
Syntax
std::stable_sort(first, last, compare)
Run this example in C++
Save the program as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson
Rank jobs while preserving arrival order
A queue or leaderboard contains entries with equal primary scores. Specify how ties are handled so the final ordering is predictable and preserves arrival order when the task requires it.
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
struct Job { std::string name; int priority; };
int main() {
std::vector<Job> jobs{{"pack", 2}, {"inspect", 1}, {"ship", 2}};
std::stable_sort(jobs.begin(), jobs.end(), [](const Job &a, const Job &b) {
return a.priority < b.priority;
});
for (const auto &job : jobs) std::cout << job.name << '\n';
return 0;
}
inspect pack ship
The comparator uses a strict less-than comparison. With equal priorities, the input order determines which job appears first.
C++ working draft for std::stable_sort
Count packs on the delivery slip
A loading desk receives four item counts in sequence. The supervisor sorts the counts from smallest to largest. Which sequence goes on the summary sheet?
Review print quantities
A print room records four job quantities, including a cancelled job. The supervisor sorts the counts from smallest to largest. Which sequence goes on the summary sheet?