How can I use Boost.Bind for complex types?

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

boost::lambda ?

+8
c ++ boost-bind boost-lambda
source share
3 answers

The map iterator will provide you with a pair , where first is the int key, and second is the value of the pair map, so if you had an iterator, you would need at least all the values ​​of it->second.first . The min_element function expects a comparison function for its third argument, so you need to build a comparison function that implements second.first from its two arguments.

We will 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 will use Boost.Lambda for our overloaded operators, allowing us to use operator< . Boost.Bind can bind member variables as well as member functions, so we will use this as well.

 #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; 

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

+6
source share
 min_element(map.begin(), map.end(), compose2(less<short>(), compose1(select1st<pair<short, float> >(), select2nd<map<int, pair<short, float> >::value_type>()), compose1(select1st<pair<short, float> >(), select2nd<map<int, pair<short, float> >::value_type>())) ).second.first; 

(Of course, someone is going to complain that this is an abuse of STL and that these extensions are not in the C ++ standard ...)

+5
source share

bind cannot do this on its own, because first and second displayed as fields, not methods (so you cannot get away with something like mem_fun ).

You could do this using your own functor, of course:

 template <typename F, typename S> struct select_first : std::binary_function<std::pair<F, S>&, F&> { F& operator()(std::pair<F, S>& toConvert) { return toConvert.first; } }; 
+2
source share

All Articles