C++中的Lambda匿名函数
1.Lambda表达式语法
在C++中,Lambda表达式(也称为匿名函数)提供了一种方便的方式来创建匿名函数对象,Lambda表达式的一般形式如下:
![Image](https://img-blog.csdnimg.cn/direct/eaf64f6952504e9a878a1a10a4280ea3.png)
这里显示了Lambda语法的基本部分:
- capture子句,又被称为捕获列表,捕获列表中的值,可以在函数体中进行访问
- 参数列表(可选),用于指定函数需要传递的参数
- mutable规范(可选)
- exception-specification(可选)
- 返回值类型(可选)
- Lambda体,即函数体
1.1 capture子句
Lambda可以在其主体中引入新的变量,还可以访问和捕获周围的范围内的变量,指定捕获变量的方式有如下几种:
- 值捕获(value capture)
- 引用捕获(reference capture)
- 隐式捕获(implicit capture)
- 初始化捕获(init-capture)
空 capture 子句[ ]
表示 lambda 表达式的主体不需要访问封闭范围内中的变量。
值捕获需要手动来指定,例如有一个变量foo
,使用[foo]
来捕获它。
引用捕获也需要手动指定,例如有个变量boo
,使用[&boo]
来捕获它。
还可以使用隐式捕获来指示如何捕获lambda体中的访问的任何外部变量:
[&]
表示通过引用的方式来捕获引用的所有变量,而[=]
表示通过值捕获来它们。可以使用隐式捕获模式,然后为特定的变量显示指出相反的模式。例如,lambda主体需要通过引用的方式访问外部变量total
,并通过值访问外部变量factor
,则下列的capture子句等效:
[&total, factor]
[factor, &total]
[&, factor]
[=, &total]
初始化捕获是使用初始化列表来捕获外部变量,可以用于按值捕获或者按引用捕获。使用的方式为[var=init]
或者[&var=init]
值捕获的示例:
#include <iostream>
int main() {
int x = 5;
auto lambda = [x] {
std::cout << "Captured value: " << x << std::endl;
};
lambda(); // Output >> Captured value: 5
return 0;
}
引用捕获的示例:
#include <iostream>
int main() {
int x = 5;
auto lambda = [&x] {
x++;
std::cout << "Updated value: " << x << std::endl;
};
lambda(); // Output >> Updated value: 6
std::cout << "Outer value: " << x << std::endl; // Output >> Outer value: 6
return 0;
}
隐式捕获示例:
#include <iostream>
int main() {
int x = 5;
auto lambda = [=] {
// x被复制到lambda中
std::cout << "Captured value: " << x << std::endl;
};
lambda(); // Output >> Captured value: 5
return 0;
}
引用捕获示例:
#include <iostream>
int main() {
int x = 5;
auto lambda = [x_copy = x] () mutable {
// x_copy是x的复制
std::cout << "Copied value: " << x_copy << std::endl;
x_copy++;
};
lambda(); // Output >> Copied value: 5
return 0;
}
1.2 参数列表
Lambda既可以捕获变量,也可以接受输入参数,Lambda的参数列表的用法类似于函数的参数列表,例如:
auto y = [] (int first, int second)
{
return first + second;
};
1.3()
立即执行
在 Lambda 表达式后面加上 ()
可以立即执行 Lambda 函数,并返回函数的结果。而不加 ()
则表示只是定义了一个 Lambda 函数,并不会立即执行。例如:
#include <iostream>
using namespace std;
int main()
{
int m = 0;
int n = 0;
[&, n] (int a) mutable { m = ++n + a; }(4);
cout << m << endl << n << endl;
}
Output
5
0
这里立即执行了,传入参数a=4
,然后执行匿名函数的函数体,执行结果m
被修改为5
,n
的值不变。
2.Lambda表达式示例
使用lambda表达式来作为函数参数传递
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5};
// 使用 Lambda 表达式作为 std::for_each 算法的参数
std::for_each(nums.begin(), nums.end(), [](int num) {
std::cout << num << " ";
});
// 输出结果:1 2 3 4 5
return 0;
}
在STL容器中进行使用
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5};
// 在 STL 容器中存储 Lambda 表达式
std::vector<std::function<int(int)>> operations = {
[](int x) { return x * 2; },
[](int x) { return x + 5; }
};
for (auto& op : operations) {
for (auto num : nums) {
std::cout << op(num) << " ";
}
std::cout << std::endl;
}
return 0;
}