Library contents

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

  1. Start with A with rank 2, B with rank 1, C with rank 2
  2. Do this Stable sort by rank
  3. Result B, A, C
B moves to the front. A and C tie, so their original order is preserved.

Syntax

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.

First output lineinspect
lesson.cpp
#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;
}
Output
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

Advertisements

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?

Given6 · 2 · 6 · 0
Worked result0 · 2 · 6 · 6

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?

Given3 · 0 · 8 · 3
Worked result0 · 3 · 3 · 8