C++11 函数对象的升级版=>lambda表达式
函数对象的缺点:
使用在泛型算法,参数传递, 比较性质/自定义操作 优先级队列, 需要专门定义出一个类
//lambda表达式语法:
//[捕获外部变量](形参列表)->返回值{操作代码}
auto func1=[]()->void{cout<<"hello world"<<endl;} func1(); 编译器根据 []()->void{cout<<"hello world"<<endl;} 产生一个函数对象 < code></"hello></"hello>
上面等价于
template<typename t="void">
class TestLamda{
public:
TestLamda(){}
void operator(){
cout<<"hello world"<<endl; } testlamda<> t1;
t1();
</"hello></typename>
[]()->void{cout<<"hello world"<<endl;} [] 相当于 testlamda(){} () operator() void {cout<<"hello operator(){ cout<<"hello world"<<endl; } < code></"hello>
示例2
auto f2=[](int a,int b)->int {int c=a+b;cout<<c<<endl; return c;} 相当于 template<typename t="int">
class TestLamda{
public:
TestLamda(){}
int operator(int a, int b){
int c= a+b;
cout<<c<<endl; return c; } < code></c<<endl;></c<<endl;>
如果lambda表达式没有返回值那么 “->返回值” 可以不要 优化如下
auto f2=[](int a,int b){int c=a+b;cout<<c<<endl; return c;}< code></c<<endl;>
关于 [捕获外部变量]
[]表示不捕获任何变量
[=] 以传值得方式捕获外部的所有变量
[&] 以传引用的方式捕获外部所有变量
[this] 捕获外部的this指针
[=,&a] 以传值的方式捕获外部的所有变量,但是a变量以传引用的方式捕获
[a,b] 以值传递的方式捕获外部a 和 b
[a,&b] 以值传递的方式捕获a, b以引用的方式传递
int a=10;
int b=20;
auto function=[&a,&b](){int temp=a;a=b;b=temp;} //实现a,b交换, 一定要 [&a,&b] 引用 或者
auto function=[&](){int temp=a;a=b;b=temp;}// 表示定义的外部变量全部以引用的方式 传入,来捕获.
int x = 200;
int y = 100;
std::function<void()> f= [&x, &y]()->void{x = x + 1; y = y + 1;};
f();
std::cout << x << "=" << y << std::endl;
</void()>
lambda 简单应用
vector<int> v1;
//排序
sort(v1.begin(),v1.end(),[](int a, int b)->bool{return a>b;})
//找到 第一个小于65的 值
auto it_find=find_if(v1.begin(),v1.end(),[](int a)->bool{return a<65;}) 打印元素 for_each( ;v1.begin()!="v1.end()" ; [](int a){cout<<a<<endl;}) 打印偶数 a){ if(a%2="=0){" cout<<a<<endl; } }) < code></65;})></int>
Original: https://www.cnblogs.com/erichome/p/16966411.html
Author: Hello_Bugs
Title: <七>lambda表达式实现原理
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/796962/
转载文章受原作者版权保护。转载请注明原作者出处!