01 / 21

Custom
Comparators

Learn how to write custom comparison functions in C++ to control exactly how sorting algorithms order your data.

C++

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?

Unsorted 42 7 23 1 sort() Default (ascending) 1 7 23 42 Custom (descending) 42 23 7 1 custom

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?

Returns true
Element a should be placed before element b
Returns false
Element a should NOT be placed before element b

Why Do We Need Them?

Descending Order
Sort numbers from largest to smallest
Custom Objects
Sort structs by a specific field (age, name, score)
Complex Rules
Sort by multiple criteria with tiebreakers

The Comparator Signature

bool compare(const Type& a, const Type& b) { return /* true if a should come before b */; }
1
Takes two const references to the element type
2
Returns bool: true means a goes before b
3
Must define strict weak ordering: if \( a < b \) is true, then \( b < a \) must be false

Strict Weak Ordering Rules

Irreflexivity comp(a, a) is always false Asymmetry if comp(a,b) then !comp(b,a) Transitivity if comp(a,b) and comp(b,c) then comp(a,c) must be true Violating these rules causes undefined behavior The sort may crash, produce wrong results, or loop forever

Three Ways to Write Comparators

Function
A standalone bool function passed by name
Lambda
An inline anonymous function defined at the call site
Functor
A struct/class with an overloaded operator()

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

1
Identify the type of elements being sorted (int, string, struct)
2
Define your ordering rule: which element should come first?
3
Write a function or lambda that takes two const references and returns bool
4
Use strict \( < \) (never \( \leq \)) to maintain strict weak ordering
5
Pass the comparator as the third argument to std::sort

Example 1: Descending Sort

// Sort integers in descending order bool descending(const int& a, const int& b) { return a > b; // a before b if a is larger } vector<int> v = {3, 1, 4, 1, 5}; sort(v.begin(), v.end(), descending); // Result: {5, 4, 3, 1, 1}

Example 2: Lambda Comparator

// Same descending sort using a lambda vector<int> v = {3, 1, 4, 1, 5}; sort(v.begin(), v.end(), [](const int& a, const int& b) { return a > b; }); // Result: {5, 4, 3, 1, 1}

Example 3: Sorting Structs

struct Student { string name; int grade; }; bool byGradeDesc(const Student& a, const Student& b) { return a.grade > b.grade; } vector<Student> students = { {"Alice", 95}, {"Bob", 87}, {"Eve", 92} }; sort(students.begin(), students.end(), byGradeDesc); // Order: Alice(95), Eve(92), Bob(87)

Example 4: Multi-Key Sorting

// Sort by grade descending, then name ascending bool multiSort(const Student& a, const Student& b) { if (a.grade != b.grade) return a.grade > b.grade; // higher grade first return a.name < b.name; // same grade: alphabetical }
Before Eve 95 Alice 95 Bob 87 After Alice 95 Eve 95 Bob 87 tiebreaker

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.

// #include <functional> vector<int> v = {3, 1, 4, 1, 5}; // Descending sort with built-in functor sort(v.begin(), v.end(), greater<int>()); // Result: {5, 4, 3, 1, 1} // Ascending (default) is the same as: sort(v.begin(), v.end(), less<int>());

Common Mistakes

✕ Using \( \leq \) instead of \( < \)
Returning a \( \leq \) b breaks strict weak ordering. Equal elements must return false, not true.
✕ Inconsistent logic
If your comparator says \( A < B \) and \( B < A \) simultaneously, std::sort triggers undefined behavior.
✕ Wrong parameter type
Comparator params must match the container element type. Passing int& for a vector of strings fails.

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

What is the sorted order?

Question 5 of 5

Which C++ syntax correctly sorts a vector v in descending order using a lambda?