lambda表达式
lambda表达式是C++11的新特性,语法糖。
lambda表达式的定义格式类似于函数,但不需要函数名,因此也称为匿名函数。
函数对象与lambda的区别
- 函数对象
函数对象作为回调函数,相对于函数或函数指针的优点是可以携带状态。
编写函数对象对应的类的代码比较多,没有普通的函数简洁。
- lambda表达式提供了更好的解决方法,它兼具函数的简洁性,也可以像函数对象那样携带状态,并且还可以捕获其所在的包围环境中的数据。
示例代码
#include
#include
#include
using namespace std;
class LessThan {
public:
bool operator()(const std::vector &a, const std::vector &b) {
return a[0] < b[0] || (a[0] == b[0] && a[1] < b[1]);
}
};
LessThan less_than;
int main() {
std::vector<std::vector> candidates = {{1, 3}, {2, 1}, {1, 2}};
// 使用 std::sort 函数进行排序
// std::sort(candidates.begin(), candidates.end(), [](const std::vector &a, const std::vector &b) -> bool {
// return a[0] < b[0] || (a[0] == b[0] && a[1] < b[1]);
// });
std::sort(candidates.begin(), candidates.end(), less_than);
// 输出排序后的结果
for (const auto& vec : candidates) {
std::cout << "[" << vec[0] << ", " << vec[1] << "] ";
}
std::cout << std::endl;
return 0;
}