首页 > C++ > 正文
Lambda表达式.html
#include <algorithm> 
#include <vector>
#include <string>
#include <iostream>
using namespace std;  
//值捕获
void mainLambda_fun1()
{
    size_t v1 = 42;
    auto f = [v1]{return v1;};
    v1 = 0;
    auto j = f();//j为42;
    cout<<u8"值捕获:"<<j<<endl;
}
//引用捕获,建议少用
void mainLambda_fun2()
{
    size_t v1 = 42;
    auto f = [&v1]{return v1;};
    v1 = 0;
    auto j = f();//j为0;
    cout<<u8"引用捕获:"<<j<<endl;
}
//加关键字mutable,可以改变它所捕获的变量的值
void mainLambda_fun3()
{
    size_t v1 = 42;
    auto f = [v1]mutable {return ++v1;};
    v1 = 0;
    auto j = f();//j为0;
    cout<<u8"加关键字mutable,可以改变它所捕获的变量的值:"<<j<<endl;
}
int main()  
{  
    system("chcp 65001");//处理命令行中文乱码
    vector<string> vecStrT{"abcd","bcde","cedf","defg","efgj"};
    string st = "bcde";
    vector<string>::iterator reslut = find_if(vecStrT.begin(),vecStrT.end(),
    [st](const string &a)->bool{return a>st;});//#include <algorithm>
    cout<<*reslut<<endl;
    printf(u8"lambda的格式:[capture list](parameter list)->return type { function body }\n");
    printf(u8"一个lambda的捕获列表和函数体必须有,其它的如果不用可以省略\n");
    printf(u8"一个lambda只有在其捕获列表中捕获一个它所在函数中的局部变量,才能在函数体中使用该变量\n");
    printf(u8"捕获列表只用于局部非static变量,lambda可以直接使用局部static变量和在它所在函数之外声明的名字\n");
    mainLambda_fun1();
    mainLambda_fun2();
    mainLambda_fun3();
    system("pause");
}
猜你喜欢
picture loss