std::sort &
Comparators
Master the C++ Standard Library's most essential sorting tool: learn how std::sort works, write custom comparators, and control the order of any data type.
What is std::sort?
std::sort is a function from the <algorithm> header that rearranges elements in a range into a specified order. By default, it sorts in ascending order using the < operator.
The Two-Argument Signature
The simplest form of std::sort takes two iterators: the beginning and end of the range you want to sort.
Why Sorting Matters
std::unique to remove duplicates efficiently.The Comparator Parameter
The three-argument form of std::sort accepts a comparator: a callable that defines the ordering relationship between two elements.
How the Comparator Decides Order
Three Ways to Write a Comparator
bool cmp(int a, int b)[](int a, int b){ ... }operator() overloaded: most flexible, can hold state.Function vs Lambda
| Free Function | Lambda | |
|---|---|---|
| Syntax | bool cmp(int a, int b) |
[](int a, int b){ ... } |
| Location | Defined outside the caller | Defined inline at the call site |
| Captures Variables | No (global scope only) | Yes (via capture list [ ]) |
| Reusability | High | Single-use typical |
| Readability | Clear when named well | Compact, near usage |
How to Apply a Custom Sort
#include <algorithm>true if the first argument should appear before the second.std::sort(v.begin(), v.end(), comp);comp(a, a) returns false (irreflexivity).Example 1: Descending Sort
To sort in descending order, the comparator should return true when a is greater than b.
Example 2: Sort by String Length
Sort a vector of strings so that shorter strings come first. If two strings have the same length, preserve their relative order (this requires std::stable_sort).
Example 3: Sorting Custom Structs
Sort a list of students by GPA descending. If GPAs are equal, break ties by name ascending (alphabetical).
Visualizing the Multi-Key Sort
The Strict Weak Ordering Rule
Your comparator must satisfy strict weak ordering, or std::sort has undefined behavior. This means:
comp(a, a) must return false. An element is not "less than" itself.comp(a, b) is true, then comp(b, a) must be false.comp(a, b) and comp(b, c), then comp(a, c) must be true.Common Mistakes
comp(a, a) returns true, causing undefined behavior.(string a, string b) copies every string on every comparison: extremely slow.comp(a,b) and comp(b,a) can both return true, the sort breaks entirely.Summary Reference
| Goal | Comparator | Alternative |
|---|---|---|
| Ascending (default) | a < b |
(none needed) |
| Descending | a > b |
std::greater<>() |
| By field | a.field < b.field |
Lambda or function |
| Multi-key | Nested if |
std::tie |
| Stable order | Same comparator | std::stable_sort |
Question 1 of 5
What is the default sorting order when you call std::sort(v.begin(), v.end()) without a comparator?
operator< by default, which produces ascending order for numeric types and lexicographic order for strings.Question 2 of 5
Which comparator lambda sorts integers in descending order?
a > b means "put larger elements first," which produces descending order. Option B uses <=, which violates strict weak ordering.Question 3 of 5
Why is using <= in a comparator dangerous?
<=, comp(a, a) returns true, violating irreflexivity. This breaks the strict weak ordering contract and leads to undefined behavior: crashes, infinite loops, or corrupted data.Question 4 of 5
Given a struct Student { string name; double gpa; };, which comparator sorts students by GPA descending?
> for descending order and const reference to avoid copies. Option C uses pass-by-value, which is inefficient. Option B sorts ascending.Question 5 of 5
What is the average time complexity of std::sort?