There is very little to learn about function objects.
They are basically a struct (or class) with an overloaded operator() and may optionally have member variables to store state.
Const correctness is important and to work with all std algorithms they need certain typedefs,which your function object gains if you inherit them from std::unary_function or std::binary_function (the references tell you which algorithms requires which predicates).
For example, a function object to compare two pair<int, int>'s might look like this:
Code:
struct less_pair:
public std::binary_function<std::pair<int, int>, std::pair<int, int>, bool>
//template arguments for binary_function are: left argument type, right argument type, return type
{
bool operator() (const std::pair<int, int>& lhv, const std::pair<int, int>& rhv) const
{
return lhv.first < rhv.first || lhv.first == rhv.first && lhv.second < rhv.second;
}
};
//usage
std::vector<std::pair<int, int> > vec;
//...
std::sort(vec.begin(), vec.end(), less_pair());
It might also be useful to familiarize yourself with the
function objects that <functional> provides (they may save you the trouble of writing your own function objects in simpler cases).
Another quite cool thing that may save you from having to write a separate functor - especially if you're just going to use it once - and may sometimes be the most readable option as well is the lambda header in boost.
In this particular case (since we need to access members of pair a lot), it is probably not that helpful though
Code:
std::sort(vec.begin(), vec.end(),
bind(&std::pair<int, int>::first, _1) < bind(&std::pair<int, int>::first, _2)
|| bind(&std::pair<int, int>::first, _1) == bind(&std::pair<int, int>::first, _2)
&& bind(&std::pair<int, int>::second, _1) < bind(&std::pair<int, int>::second, _2)
);