C++ Lambda 表达式与函数对象
Lambda 是匿名函数对象,简洁且功能强大,广泛用于 STL 算法。
1. 基本语法
[capture](parameters) -> return_type { body }
#include <algorithm>
std::vector<int> nums = {1, 2, 3, 4};
// 过滤偶数
nums.erase(std::remove_if(nums.begin(), nums.end(), [](int n) { return n % 2 == 0; }), nums.end());2. 捕获方式
[=]:值捕获(拷贝)[&]:引用捕获[this]:捕获当前对象[a, &b]:混合
int factor = 2;
auto multiply = [factor](int x) { return x * factor; };3. 泛型 Lambda(C++14)
auto add = [](auto a, auto b) { return a + b; };
std::cout << add(3, 4); // 7
std::cout << add(1.2, 3.4); // 4.64. 存储 Lambda(使用 std::function)
std::function<int(int)> func = [](int x) { return x * 2; };Lambda 是现代 C++ 编程的必备工具。
