让我们需要找到一个具有给定字段最小值的元素。
#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 功能。
最佳答案
你可以创建那些助手:
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));
关于c++ - 使用给定字段的最小值在容器中查找元素的最紧凑方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40373699/