【问题标题】:The most compact way to find an element in container with the minimum value of given field在容器中查找具有给定字段最小值的元素的最紧凑方法
【发布时间】:2016-11-02 06:28:15
【问题描述】:

我们需要找到给定字段的最小值的元素。

#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 或其他 boost 功能最紧凑的方法是什么?
也许像 std::less 和 boost::bind(&Item::a) 组合。

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

【问题讨论】:

  • 使用range-v3 及其projection,它将是auto it = ranges::min_element(items, std::less&lt;&gt;{}, &amp;Item::a);,但这确实符合您的要求。
  • 对于最简洁的答案,也许您应该通过Code Golf 向专家求助 - 但请务必仔细阅读他们的帮助,并使用沙箱(他们确实喜欢非常精确的问题!)
  • 最紧凑的不需要,"boost::min_element(items, boost::bind(&Item::a, _1)

标签: c++ boost-bind


【解决方案1】:

您可以创建这些助手:

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

【讨论】:

  • 这是解决问题的好方法。我在 boost 实现中寻找类似的东西,但找不到。
【解决方案2】:

你可以只传递一个函数:

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

【讨论】:

  • 是的。但是“没有明确的谓词结构声明”写得不准确。暗示“没有明确的谓词结构或函数声明”。
【解决方案3】:

知道了:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    相关资源
    最近更新 更多