I was reading a StackOverFlow post regarding sorting a vector of pairs by the second element of the pair. The most obvious answer was to create a predicate, but one answer that used boost caught my eye.
std::sort(a.begin(), a.end(),
boost::bind(&std::pair<int, int>::second, _1) <
boost::bind(&std::pair<int, int>::second, _2));
I’ve been trying to figure out how boost::bind works, or at least just how to use it, but I can’t figure out what the purpose of the placeholder arguments _1 and _2 are, and the boost documentation doesn’t sink in at all.
Could anyone explain this specific usage of boost::bind?
P.S. Original question: How do I sort a vector of pairs based on the second element of the pair?
This expression:
namely, the use of the
<operator actually defines a functor between two other functors, both of which defined bybind.The functor expected by sort needs to have an
operator()which looks like this:when you’re creating a functor using boost’s
<then the name holders_1and_2correspond toarg1andarg2of the functor you’re creating.The
bindcall create a functor that calls::secondofarg1andarg2With any luck, the introduction of lambdas in C++0x will make expressions like this obsolete.