0
0
CppHow-ToBeginner · 3 min read

How to Sort with Custom Comparator in C++

In C++, you can sort a container using std::sort with a custom comparator by passing a function, function object, or lambda that defines the sorting order. The comparator should take two elements and return true if the first should come before the second.
📐

Syntax

The std::sort function can take a custom comparator as its third argument. This comparator defines how two elements are compared during sorting.

  • std::sort(begin, end, comparator);
  • begin and end are iterators to the container's start and end.
  • comparator is a callable that takes two elements and returns true if the first element should come before the second.
cpp
std::sort(container.begin(), container.end(), comparator);
💻

Example

This example shows sorting a vector of integers in descending order using a lambda as a custom comparator.

cpp
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {5, 2, 9, 1, 5, 6};

    // Sort in descending order using a lambda comparator
    std::sort(numbers.begin(), numbers.end(), [](int a, int b) {
        return a > b; // true if a should come before b
    });

    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    return 0;
}
Output
9 6 5 5 2 1
⚠️

Common Pitfalls

Common mistakes when using custom comparators include:

  • Returning true for equality, which breaks strict weak ordering.
  • Using a comparator that does not define a consistent order, causing undefined behavior.
  • Forgetting to pass the comparator to std::sort, resulting in default ascending order.

Always ensure your comparator returns true only when the first argument should come before the second, and false otherwise.

cpp
/* Wrong comparator: returns true for equality, breaks sorting */
std::sort(vec.begin(), vec.end(), [](int a, int b) {
    return a >= b; // Incorrect: should not return true when a == b
});

/* Correct comparator: strict greater-than for descending order */
std::sort(vec.begin(), vec.end(), [](int a, int b) {
    return a > b;
});
📊

Quick Reference

ConceptDescriptionExample
std::sortSorts elements in a rangestd::sort(v.begin(), v.end());
Custom comparatorDefines custom order for sorting[](int a, int b) { return a > b; }
Comparator returnReturns true if first element goes before secondreturn a < b;
Lambda comparatorInline anonymous function for sortingstd::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });

Key Takeaways

Use std::sort with a custom comparator to define any sorting order.
The comparator must return true only if the first element should come before the second.
Lambdas are a concise way to write custom comparators inline.
Avoid returning true when elements are equal to maintain correct sorting behavior.
Always pass the comparator as the third argument to std::sort.