Comparator Using Functor (Function Object)

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.

Example

The below example shows the program to create a comparator using a functor.

C++




// C++ program to create comparator using functor
  
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
  
// defining Functor (Function Object)
struct Comparator {
    bool operator()(int a, int b) const
    {
        // Custom comparison logic
        return a < b; // this sorts in ascending order
    }
};
  
int main()
{
    // Creating a vector of integers
    vector<int> myVec = { 9, 2, 4, 1, 6, 3 };
  
    // Using sort() with a functor (function object)
    sort(myVec.begin(), myVec.end(), Comparator());
  
    // Printing the sorted vector
    cout << "Sorted Vector: ";
    for (int i : myVec) {
        cout << i << " ";
    }
    cout << endl;
  
    return 0;
}


Output

Sorted Vector: 1 2 3 4 6 9 

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.

Similar Reads

How to Create a Comparator in C++?

In C++, we can create a comparator function using four methods. They are:...

1. 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....

2. Comparator Using Lambda Expression

...

3. Comparator Using Functor (Function Object)

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....

4. Function Object with State (Using a Class)

...

Application of Comparator in C++

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....

Conclusion

...

Contact Us