lambda表达式
很多语言都有增加了lambda表达式,我没想到c++也增加了,lambda表达式是一个不错的语法糖
基本结构
[] () mutable throw() -> int
{
}
捕获子句[]
这个东西是用来捕获外部变量的
不捕获任何变量
#include <iostream>
#include <string>
using namespace std;
int main() {
int a = 123;
auto func = []() {
cout << "hello lambda exp";
};
func();
return 0;
}
捕获一个变量
#include <iostream>
#include <string>
using namespace std;
int main() {
int a = 123;
auto func = [a]() {
cout << a;
};
func();
return 0;
}
捕获所有变量的拷贝
拷贝就说明变量在表达式内部只可读而不可更改(即使更改,这个更改也不会传递到外部),当然值传递只能捕获在lambda函数之前的变量
#include <iostream>
#include <string>
using namespace std;
int main() {
int a = 123;
int b = 456;
string c = "tinuv";
auto func = [ = ]() {
cout << a << "\n";
cout << b << "\n";
cout << c << "\n";
cout << d;
};
func();
return 0;
}
引用捕获
#include <iostream>
#include <string>
using namespace std;
int main() {
int a = 123;
int b = 456;
auto func = [ &a, &b ]() {
cout << a << "\n";
cout << b << "\n";
b = 10;
};
a = 678;
func();
cout << b;
return 0;
}
输出结果是
678
456
10
除此之外还可以捕获this指针,这主要在面向对象中使用,这里不介绍
mutable关键字
如果不使用mutable关键字的话,修改值传递的变量是会报错的,但如果使用mutable关键字的话就可以更改值传递的变量了,但是,即使修改了也==不能传递到外部==
#include <iostream>
#include <string>
using namespace std;
int main() {
int a = 123;
int b = 456;
auto func = [a, b]()mutable {
cout << a << "\n";
cout << b << "\n";
b = 10;
cout << b << "\n";
};
func();
cout << b;
return 0;
}
throw()子句
这里暂时不介绍
参数列表,返回类型,函数主体
都跟其他语言的差不多,就不多说了
??正文结束??
本文深入探讨C++中的Lambda表达式,讲解其基本结构、捕获子句、引用捕获及mutable关键字的使用,通过实例展示如何在C++代码中有效利用Lambda表达式。
1078

被折叠的 条评论
为什么被折叠?



