【问题标题】:How to create a comparator with Boost?如何使用 Boost 创建比较器?
【发布时间】:2010-07-17 10:13:58
【问题描述】:

我是 Boost 新手,但不是函数式编程的新手,我正在尝试了解 Boost 可以在哪些方面帮助我。

我有一个二维点列表,我想提取最小x 坐标。 Point 类有一个成员函数float x() const 所以我可以使用boost::mem_fn 如下:

boost::mem_fn(&Point::x)

但为了使用std::min_element,我需要一个支持bool operator()(Point const &, Point const &) 的对象。像这样虚构的compare_by

leftmostPoint = std::min_element(
    points.begin(), points.end(),
    boost::compare_by(boost::mem_fn(&Point::x)));

我可以使用 Boost 来构建这样的比较,还是我需要自己做这个?


更新:这是我自己的实现,但我仍然有兴趣了解 Boost 是如何为我做到这一点的。

template<typename F>
class CompareBy {
    F const d_f;
    public:
        CompareBy(F f) : d_f(f) { }
        template<typename T>
        bool operator()(T const &a, T const &b) const {
            return d_f(a) < d_f(b);
        }
};

template<typename F>
CompareBy<F> compare_by(F f) {
    return CompareBy<F>(f);
}

用法:同上,减去boost:: 命名空间。

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

    我不知道有任何类似于您的 Compare_by 的 boost 构造。
    但是, boost::bind 可以解决问题。

    Point leftmostPoint = *std::min_element(points.begin(), points.end(),
       boost::bind(std::less<Point::type_x>(), 
           boost::bind( &Point::x, _1 ), boost::bind( &Point::x, _2 )));
    

    是的,那不漂亮:/
    幸运的是,有一个可用的语法快捷方式,因为 boost::bind 生成的函数对象重载了很多常用的运算符,比如

    Point leftmostPoint2 = *std::min_element(points.begin(), points.end(),
    boost::bind( &Point::x, _1 ) < boost::bind( &Point::x, _2 ));
    

    但我认为只有 C++0X 的 lambda 才能真正做到简洁清晰:

    Point leftmostPoint3 = *std::min_element(points.begin(), points.end(),
    [](const Point& p1, const Point& p2){ return p1.x < p2.x; });
    

    【讨论】:

    • 我认为lamba需要一个布尔返回类型,即[](const Point&amp; p1, const Point&amp; p2) -&gt; bool
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    相关资源
    最近更新 更多