I\'ve found some good examples of functors on SO like this one, and all the convincing examples seem to use state in the class that defines operator()
.
Another reason is that sometimes one comparison function is not enough. Let's say we have a vector of pointers:
struct X { string name; };
vector> v;
Now if we want to sort the vector by name
, we have to define our own predicate for the sort
function:
struct Cmp1
{
bool operator()(const shared_ptr& left, const shared_ptr& right) const
{ return left->name < right->name; }
};
That's cool, but what do we do when we need to find the objects with specific name? To work with equal_range
, the predicate needs to have two different comparison functions:
struct Cmp2
{
bool operator()(const shared_ptr& left, const string& right) const
{ return left->name < right; }
bool operator()(const string& left, const shared_ptr& right) const
{ return left < right->name; }
};
This allows us to call equal_range
with a string
name object:
equal_range(v.begin(), v.end(), name, Cmp2())