Function Object with State (Using a Class)

In this method, we create a functor with a parameterized constructor that stores additional state information for comparison. This information can be anything that you want to use as a metric for state.

Example

The below example shows a program to create custom comparator using a class.

C++




//C++ program to create custom comparator using a class.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
  
// Function object with state
class CustomComparator {
public:
    CustomComparator(int baseValue) : baseValue_(baseValue) {}
  
    bool operator()(int a, int b) const {
        // Custom comparison logic involving state
        return (a % baseValue_) < (b % baseValue_);
    }
  
private:
    int baseValue_;
};
  
int main() {
    // Creating a vector of integers
    vector<int> myVector = {12, 24, 8, 13, 27, 40};
  
    // Using sort with a function object with state
    sort(myVector.begin(), myVector.end(), CustomComparator(5));
  
    // printing the sorted vector
    cout << "Sorted Vector: ";
    for (int num : myVector) {
        cout << num << " ";
    }
    cout << endl;
  
    return 0;
}


Output

Sorted Vector: 40 12 27 8 13 24 

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

...