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; } |
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.
Contact Us