01 / 20

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.

C++ STL Algorithms

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.

#include <algorithm> #include <vector> std::vector<int> v = {5, 2, 8, 1, 9}; std::sort(v.begin(), v.end()); // v is now {1, 2, 5, 8, 9}

The Two-Argument Signature

The simplest form of std::sort takes two iterators: the beginning and end of the range you want to sort.

// Syntax: std::sort(first, last); // first: iterator to the beginning // last: iterator past the end int arr[] = {4, 1, 3}; std::sort(arr, arr + 3); // arr is now {1, 3, 4}

Why Sorting Matters

Binary Search
Sorted data enables \( O(\log n) \) search instead of \( O(n) \) linear scan.
Deduplication
Sort first, then use std::unique to remove duplicates efficiently.
Greedy Algorithms
Many competitive programming problems require custom-sorted input as a first step.

The Comparator Parameter

The three-argument form of std::sort accepts a comparator: a callable that defines the ordering relationship between two elements.

// Syntax: std::sort(first, last, comparator); // The comparator returns true if // the first argument should come // BEFORE the second argument.

How the Comparator Decides Order

comp(a, b) Returns bool a b true a before b false b before a Comparator Decision Flow Called repeatedly during sort

Three Ways to Write a Comparator

Free Function
A standalone function with the right signature: bool cmp(int a, int b)
Lambda Expression
An inline anonymous function: [](int a, int b){ ... }
Functor (struct)
A struct with 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

1
Include the header: #include <algorithm>
2
Identify your ordering rule: what does "a comes before b" mean for your problem?
3
Write the comparator: return true if the first argument should appear before the second.
4
Pass it as the third argument: std::sort(v.begin(), v.end(), comp);
5
Verify strict weak ordering: ensure 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.

std::vector<int> v = {3, 1, 4, 1, 5}; // Lambda comparator std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; // larger first }); // v is now {5, 4, 3, 1, 1}

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).

std::vector<std::string> words = { "cherry", "fig", "apple", "kiwi" }; std::stable_sort(words.begin(), words.end(), [](const std::string& a, const std::string& b) { return a.size() < b.size(); }); // {"fig", "kiwi", "apple", "cherry"}

Example 3: Sorting Custom Structs

Sort a list of students by GPA descending. If GPAs are equal, break ties by name ascending (alphabetical).

struct Student { std::string name; double gpa; }; std::vector<Student> students = { {"Alice", 3.8}, {"Bob", 3.9}, {"Carol", 3.8} }; std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) { if (a.gpa != b.gpa) return a.gpa > b.gpa; return a.name < b.name; }); // {Bob 3.9, Alice 3.8, Carol 3.8}

Visualizing the Multi-Key Sort

BEFORE AFTER sort Alice 3.8 GPA Bob 3.9 GPA Carol 3.8 GPA Bob 3.9 Highest Alice 3.8 A < C Carol 3.8 A < C Primary key: GPA descending Tiebreaker: name ascending

The Strict Weak Ordering Rule

Your comparator must satisfy strict weak ordering, or std::sort has undefined behavior. This means:

1
Irreflexivity: comp(a, a) must return false. An element is not "less than" itself.
2
Asymmetry: if comp(a, b) is true, then comp(b, a) must be false.
3
Transitivity: if comp(a, b) and comp(b, c), then comp(a, c) must be true.

Common Mistakes

✕ Using <= instead of <
Violates strict weak ordering. comp(a, a) returns true, causing undefined behavior.
✕ Forgetting const reference
Passing by value (string a, string b) copies every string on every comparison: extremely slow.
✕ Inconsistent logic
If 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?

Question 2 of 5

Which comparator lambda sorts integers in descending order?

Question 3 of 5

Why is using <= in a comparator dangerous?

Question 4 of 5

Given a struct Student { string name; double gpa; };, which comparator sorts students by GPA descending?

Question 5 of 5

What is the average time complexity of std::sort?