Comparator Using Lambda Expression
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.
Example
The below example shows the program to create a comparator using the lambda function.
C++
// C++ program to create comparator using Lambda function #include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { // Creating a vector of integers vector< int > myVec = { 4, 3, 8, 1, 7, 2 }; // Using sort() with a lambda function sort(myVec.begin(), myVec.end(), []( int a, int b) { // Custom comparison logic return a < b; // this sorts in ascending order }); // printing sorted vector cout << "Sorted Vector: " ; for ( int i : myVec) { cout << i << " " ; } cout << endl; return 0; } |
Sorted Vector: 1 2 3 4 7 8
Comparator in C++
In C++, a comparator is a function or a function (an object that acts like a function) that is used to compare elements. It is widely used in sorting algorithms or in data structures like std::sort or std::priority_queue to define custom sorting orders. It can be used to define specific rules for comparing elements, influencing the order in which they appear.
The comparator function generally takes two parameters (values to compare) and returns a boolean value based on their comparison. Such functions are also called binary predicate. Although, there is no limitation on the number or parameters the comparator function can take.
Contact Us