C++11 函数对象的升级版=>lambda表达式

函数对象的缺点:
使用在泛型算法,参数传递, 比较性质/自定义操作 优先级队列, 需要专门定义出一个类

//lambda表达式语法:
//[捕获外部变量](形参列表)->返回值{操作代码}
auto func1=[]()->void{cout<<"hello world"<<endl;}
func1();
//编译器根据 []()->void{cout<<"hello world"<<endl;} 产生一个函数对象

上面等价于

template<typename T=void>
class TestLamda{
public:
    TestLamda(){}
    void operator(){
        cout<<"hello world"<<endl;
    }
}
TestLamda<> t1;
t1();
[]()->void{cout<<"hello world"<<endl;}
[] 相当于   TestLamda(){}
() 相当于   operator()
void 相当于  void operator()
{cout<<"hello world"<<endl;}  相当于
     void operator(){
        cout<<"hello world"<<endl;
     }

示例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;
    }
}

如果lambda表达式没有返回值那么 "->返回值" 可以不要 优化如下
auto f2=[](int a,int b){int c=a+b;cout<<c<<endl; return c;}

关于 [捕获外部变量]
[]表示不捕获任何变量
[=] 以传值得方式捕获外部的所有变量
[&] 以传引用的方式捕获外部所有变量
[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;}// 表示定义的外部变量全部以引用的方式 传入,来捕获.

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;})
//打印偶数
for_each( ;v1.begin()!=v1.end() ; [](int a){
   if(a%2==0){
      cout<<a<<endl;
   }
   })
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。