Custom
Comparators
Learn how to write custom comparison functions in C++ to control exactly how sorting algorithms order your data.
What Does Sorting Really Mean?
Sorting means arranging elements in a specific order. By default, std::sort arranges numbers from smallest to largest and strings alphabetically. But what if you need a different order?
What is a Comparator?
A comparator is any callable that takes two elements and returns a bool. It answers one question: should the first element come before the second in the sorted order?
Why Do We Need Them?
The Comparator Signature
Strict Weak Ordering Rules
Three Ways to Write Comparators
Function vs Lambda vs Functor
| Function | Lambda | Functor | |
|---|---|---|---|
| Syntax | Named function | Inline [](){} | struct + operator() |
| Reusable | ✓ Yes | Only if stored | ✓ Yes |
| Can capture state | ✕ No | ✓ Yes | ✓ Yes |
| Best for | Simple, global | One-time use | Complex logic |
How to Write a Custom Comparator
Example 1: Descending Sort
Example 2: Lambda Comparator
Example 3: Sorting Structs
Example 4: Multi-Key Sorting
Built-in: greater<T>
C++ provides built-in functors in the <functional> header for common comparisons. You do not need to write your own comparator for simple ascending/descending sorts.
Common Mistakes
Quick Reference Table
| Goal | Comparator Returns | Example |
|---|---|---|
| Ascending | \( a < b \) | less<int>() |
| Descending | \( a > b \) | greater<int>() |
| By field | \( a.\text{field} < b.\text{field} \) | Custom function |
| Multi-key | Nested if-return | Nested if-return |
| Absolute value | \( |a| < |b| \) | Lambda |
Question 1 of 5
A custom comparator for std::sort must return:
Question 2 of 5
What is the output of sorting {4, 2, 7, 1} with comparator return a > b;?
Question 3 of 5
Why is using return a \( \leq \) b; in a comparator dangerous?
Question 4 of 5
Given the struct and comparator:
What is the sorted order?
Question 5 of 5
Which C++ syntax correctly sorts a vector v in descending order using a lambda?
[](const int& a, const int& b){ return a > b; }. Option (a) passes a name, not a lambda. Option (b) passes the vector directly instead of iterators. Option (c) uses member function syntax which does not exist for vectors.