Search code examples
c++boost-bindboost-lambda

How can I use Boost.Bind on compound types?


I have std::map<int, std::pair<short, float> >, and I need to find the minimal short in this map. How can I use boost::bind with std::min_element() for this?

boost::lambda?


Solution

  • The map iterator will give you a pair where first is the int key and second is the map's pair value, so if you had an iterator it, you'd want the minimum of all the it->second.first values. The min_element function expects a comparison function for its third argument, so you need to build a comparison function that projects second.first of its two arguments.

    We'll start with some typedefs to make the code more readable:

    typedef std::pair<short, float> val_type;
    typedef std::map<int, val_type> map_type;
    map_type m;
    

    We're going to use Boost.Lambda for its overloaded operators, allowing us to use operator<. Boost.Bind can bind member variables as well as member functions, so we'll take advantage of that, too.

    #include <boost/bind.hpp>
    #include <boost/lambda/lambda.hpp>
    using boost::bind;
    
    // Comparison is (_1.second.first < _2.second.first)
    std::cout <<
      std::min_element(m.begin(), m.end(),
        bind(&val_type::first, bind(&map_type::iterator::value_type::second, _1))
        <
        bind(&val_type::first, bind(&map_type::iterator::value_type::second, _2))
      )->second.first;
    

    That will also work with boost::lambda::bind.