C/C++ Arena

Step 5 of 5

operator< and sorting

Many standard library tools need to know how to order your objects: std::sort, std::set, std::map keys, std::min and std::max. By default they all use operator<. Define it, and your type works with all of them.

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

struct Task {
    std::string name;
    int priority;
};

bool operator<(const Task& a, const Task& b) {
    if (a.priority != b.priority) {
        return a.priority > b.priority;
    }
    return a.name < b.name;
}

int main() {
    std::vector<Task> tasks = {{"email", 1}, {"deploy", 3}, {"backup", 3}, {"lunch", 2}};
    std::sort(tasks.begin(), tasks.end());
    for (const Task& t : tasks) std::cout << t.name << " ";
    std::cout << "\n";
}
backup deploy lunch email 

"Less than" means "comes first"

operator< doesn't have to mean numerically smaller. It answers "should a come before b?" Here higher priority comes first, so for priorities it uses >. Ties are broken alphabetically by name. This "compare the most important key; if equal, compare the next" pattern is how multi-key sorting always works.

It must be a consistent ordering

std::sort requires a strict weak ordering. In practice:

Breaking these (for example using <=) is undefined behavior: sort can misorder elements, loop forever, or crash.

Your turn: define operator< for Player so sorting puts the most kills first, and for equal kills, the name alphabetically first.

Previous: operator[]