![]() |
VOOZH | about |
A custom comparator in C++ is a way to tell a container (like set or sort) how to compare and order elements differently than the default. Instead of using the usual "less than" (<), we can define our own rule.
For example, you can make it sort in descending order or by a specific property of a complex object. It's like giving the container our own sorting instructions.
In C++, we can create a comparator function using four methods. They are:
In this method, we define a function that implements the comparison logic and returns some value. Then we use the pointer to this function as the comparator.
Sorted Vector: 1 2 3 4 5 7
Lambda expressions can be used to declare the inline function definitions. We can also use the lambda expression to create a comparator just like we can do with function. Moreover, we can declare the lambda expression in a place where the comparator is required.
Sorted Vector: 1 2 3 4 7 8
A functor (Function Object) is a class or struct that overloads the operator() such that it behaves as a function when called. We can also use such objects as a comparator by defining the comparison logic inside the () operator overloading function.
Sorted Vector: 1 2 3 4 6 9
In C++, comparator is widely used in many different cases. Some of the common application of comparators is as follows:
It can be used to count and sort characters in the string based on increasing frequency using a custom comparator.
Example
The below example demonstrates the use of comparator to sort the characters in increasing frequency.
oooollleeH
It can be used to count and sort characters in the string based on increasing frequency and same frequency using a custom comparator.
Example
oooollleeekhg
It is used to sort a vector of integers based on the number of set bits using a lambda function as the custom comparator.
Example
1 8 2 5 17 13
We can used comparator to sort a vector of integers to segregate even and odd numbers, placing even numbers before odd numbers.
Example
after segregation: 2 4 6 1 3 5 7