lambda高级使用

[TOC]

lambda高级使用

捕获列表

lambda 表达式还可以通过捕获列表捕获一定范围内的变量:

  • [] 不捕获任何变量。
  • [&] 捕获外部作用域中所有变量,并作为引用在函数体中使用(按引用捕获)。
  • [=] 捕获外部作用域中所有变量,并作为副本在函数体中使用(按值捕获)。
  • [=,&foo] 按值捕获外部作用域中所有变量,并按引用捕获 foo 变量。
  • [bar] 按值捕获 bar 变量,同时不捕获其他变量。
  • [this] 捕获当前类中的 this 指针,让 lambda 表达式拥有和当前类成员函数同样的访问权限。如果已经使用了 & 或者 =,就默认添加此选项。捕获 this 的目的是可以在 lamda 中使用当前类的成员函数和成员变量。

使用方式

捕获

  1. 没有捕获的时候,我们将该lambda变量可以看成函数指针
  2. 有捕获的时候,我们将该lambda表达式堪称仿函数

使用方法

  1. 使用function

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    #include "iostream"
    #include "functional"
    #include "vector"

    int main()
    {
    int a{9};
    int b{10};
    [a,b](int x)->void{
    std::cout<<a+b<<std::endl<<x<<std::endl;
    }(88);
    std::function<void(int,std::string)> func{[](int num,std::string S)->void{
    std::cout<<"num= "<<num<<" name= "<<S<<std::endl;
    }};
    func(1,"chg");
    return 0;
    }

  2. 使用bind

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    int main()
    {
    int a{9};
    int b{10};
    [a,b](int x)->void{
    std::cout<<a+b<<std::endl<<x<<std::endl;
    }(88);
    auto f2= std::bind([](int num,std::string S)->void{
    std::cout<<"num= "<<num<<" name= "<<S<<std::endl;
    },std::placeholders::_1,std::placeholders::_2);
    f2(2,"zjy");
    return 0;
    }


lambda高级使用
https://tsy244.github.io/2023/03/26/cpp/lambda高级使用/
Author
August Rosenberg
Posted on
March 26, 2023
Licensed under