我想知道是否可以从 lambda 表达式创建一个实际的仿函数对象。我不这么认为,但如果不是,为什么?
为了说明,给定下面的代码,它使用 x 和 y 坐标的各种策略对点进行排序:
#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>
struct Point
{
Point(int x, int y) : x(x), y(y) {}
int x, y;
};
template <class XOrder, class YOrder>
struct SortXY :
std::binary_function<const Point&, const Point&, bool>
{
bool operator()(const Point& lhs, const Point& rhs) const
{
if (XOrder()(lhs.x, rhs.x))
return true;
else if (XOrder()(rhs.x, lhs.x))
return false;
else
return YOrder()(lhs.y, rhs.y);
}
};
struct Ascending { bool operator()(int l, int r) const { return l<r; } };
struct Descending { bool operator()(int l, int r) const { return l>r; } };
int main()
{
// fill vector with data
std::vector<Point> pts;
pts.push_back(Point(10, 20));
pts.push_back(Point(20, 5));
pts.push_back(Point( 5, 0));
pts.push_back(Point(10, 30));
// sort array
std::sort(pts.begin(), pts.end(), SortXY<Descending, Ascending>());
// dump content
std::for_each(pts.begin(), pts.end(),
[](const Point& p)
{
std::cout << p.x << "," << p.y << "\n";
});
}
表达式std::sort(pts.begin(), pts.end(), SortXY<Descending, Ascending>());
按 x 值降序排序,然后按 y 值升序排序。它很容易理解,我不确定我是否真的想在这里使用 lambda 表达式。
但是如果我想用 lambda 表达式替换 Ascending/Descending,你会怎么做呢?以下不有效:
std::sort(pts.begin(), pts.end(), SortXY<
[](int l, int r) { return l>r; },
[](int l, int r) { return l<r; }
>());
最佳答案
出现这个问题是因为 SortXY 只接受类型,而 lambda 是对象。您需要重新编写它,以便它接受对象,而不仅仅是类型。这是函数对象的基本用法 - 查看 std::for_each
如何不采用类型,而是采用对象。
关于c++ - 从 lambda 表达式创建仿函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4803531/