Comparator Using Function Pointer
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.
Example
The below example shows the program to create a comparator using a function pointer.
C++
// C++ program to create comparator using function pointer #include <algorithm> #include <iostream> #include <vector> using namespace std; // Custom comparison function bool customComparison( int a, int b) { // Custom comparison logic return a < b; // it sorts in ascending order } int main() { // Creating a vector of integers vector< int > myVec = { 7, 5, 2, 1, 4, 3 }; // Using sort with a function pointer sort(myVec.begin(), myVec.end(), customComparison); // Displaying the sorted vector cout << "Sorted Vector: " ; for ( int num : myVec) { cout << num << " " ; } cout << endl; return 0; } |
Sorted Vector: 1 2 3 4 5 7
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