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

标签 c++ boost-bind

让我们需要找到一个具有给定字段最小值的元素。

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

相关文章:

c++ - n2439 "Extending move semantics to *this"对非静态成员函数的限制背后的基本原理

c++ - 如何绘制环绕圆圈的文字?

c++ - std::string 的函数指针的 typedef 不起作用

c++ - 原始函数指针与 boost::bind 返回值

c++ - 使用 std::shared_ptr 而不是 boost::shared_ptr 时编译失败

c++ - 查找表/数组索引的数据类型

c++ - 使用 *void 作为 static_cast 的缓冲区

c++ - 重用 boost::bind 调用的返回值的正确方法是什么?

c++ - boost::bind 在存储时不保存部分参数

c++ - 是否可以在 C++/SDL 中指定图像/ Sprite 的大小?