使用给定字段的最小值在容器中查找元素的最紧凑方法

The most compact way to find an element in container 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());

使用 boost::bind 或其他没有显式谓词结构声明的提升功能,最紧凑的方法是什么?
也许像 std::less 和 boost::bind(&Item::a) 组合。

注意:不使用 C++11 功能。

你可以只传递一个函数:

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

// ...

std::vector<Item>::const_iterator minA = boost::min_element(items, compare_by_a);

您可以创建这些助手:

template <typename T, typename M>
class CompareByMember
{
public:
    explicit CompareByMember(M m) : m(m) {}

    bool operator()(const T& x, const T& y) const
    {
        return x.*m < y.*m;
    }
private:
    M m;
};

template <typename T, typename Ret>
CompareByMember<T, Ret (T::*)> MakeCompareByMember(Ret (T::*m))
{
    return CompareByMember<T, Ret (T::*)>(m);
}

然后调用

std::vector<Item>::const_iterator minA =
    boost::min_element(items, MakeCompareByMember(&Item::a));

知道了:

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