Custom Comparators
Control ordering.
Why Custom Comparators?
By default, ordered containers sort with std::less (ascending). A custom comparator lets you change that order, for example descending or by a specific field.
#include <iostream>
#include <set>
int main() {
std::set<int> ascending{3, 1, 2};
for (int x : ascending) std::cout << x << ' ';
std::cout << '\n';
return 0;
}Descending with std::greater
The simplest custom comparator is the standard functor std::greater, which sorts in descending order.
#include <iostream>
#include <set>
#include <functional>
int main() {
std::set<int, std::greater<int>> s{3, 1, 2};
for (int x : s) std::cout << x << ' ';
std::cout << '\n';
return 0;
}All lessons in this course
- std::map
- std::set
- multimap and multiset
- Custom Comparators