【发布时间】: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:: 命名空间。
【问题讨论】: