Search code examples
c++boost-bind

The most compact way to find an element in container with the minimum value of given field


Let's we need to find an element with the minimum value of given field.

#include <boost/range/algorithm/min_element.hpp>
#include <vector>

struct Item
{
    size_t a;
    size_t b;
};

struct CompareByA
{
    bool operator()(const Item& x, const Item& y) const
    {
        return x.a < y.a;
    }
};

std::vector<Item> items;
//... fill
std::vector<Item>::const_iterator minA = boost::min_element(items, CompareByA());

What is the most compact way to do it using boost::bind or other boost features without explicit predicate struct declaration?
Maybe something like std::less and boost::bind(&Item::a) combination.

NOTE: Without using C++11 features.


Solution

  • Got it:

    #include <boost/range/algorithm/min_element.hpp>
    #include <boost/bind.hpp>
    #include <vector>
    
    struct Item
    {
        size_t a;
        size_t b;
    };
    
    std::vector<Item> items;
    //... fill
    std::vector<Item>::iterator minA = 
        boost::min_element(items, boost::bind(&Item::a, _1) < boost::bind(&Item::a, _2));