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);beginandendare iterators to the container's start and end.comparatoris a callable that takes two elements and returnstrueif 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
truefor 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
| Concept | Description | Example |
|---|---|---|
| std::sort | Sorts elements in a range | std::sort(v.begin(), v.end()); |
| Custom comparator | Defines custom order for sorting | [](int a, int b) { return a > b; } |
| Comparator return | Returns true if first element goes before second | return a < b; |
| Lambda comparator | Inline anonymous function for sorting | std::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.