[C/C++] C++之Lambda表达式(匿名函数)

Lambda表达式也叫匿名函数,有时候也叫闭包(Closure)

参考视频注意视频中捕获变量部分有错误,按本博客为准

1. 定义

[OuterVar](int x, int y) -> int {
  return OuterVar + x + y;
};
  • [OuterVar]:捕获变量;
  • (int x, int y):参数列表;
  • -> int:返回类型为int,实际上返回值类型可以忽略的,因为编译器可以自行推断它的类型,所以 -> int 可以省略;

1.1 捕获变量(Capture Clause)

这个部分的功能是让匿名函数可以访问外部变量

  • 如果为空,表示不捕获任何变量。
  • 如果在某个Class中使用匿名函数,还可以用this捕获当前实例的指针,例如如果下面示例的匿名函数是在类中,可以使用[N, &M, this],在C++17标准之后,还可以使用 *this 按值捕获该实例;
  • C++14标准之后,还可以引入新的变量,例如下面示例中使用[N, &M, K = 5],引入新的变量K,并赋值5;
#include <iostream>
using namespace std;
int main(){
  int N = 100, M = 10;
  // 其中N是值传递,&M是引用传递
  auto lambda = [N, &M](int val) -> int{
    M = 20;
    return N * val;
  };
  cout << lambda(10) << endl;
  cout << M << endl;
  return 0;
}
/**
 * 1000
 * 20
 */

/*-----(附)使用this-----*/
#include <iostream>
using namespace std;
class A{
  int a = 10;
public:
  void demo(){
    auto lambda = [this](int val) -> int{
      this->a = 2333;
      return a * val;
    };
    cout << lambda(10) << endl;
  }
};
int main()
{
  A a;
  a.demo();
  return 0;
}
/**
 * 23330
 */

其他情况

  • 隐式捕获
    • [&]:按照引用传递捕获封闭范围中的所有变量
    • [=]:按照值传递捕获封闭范围中的所有变量
  • 隐式捕获+显式捕获(隐式捕获必须放在显示捕获前面):
    • [=, &M]:指定外部变量M使用引用传递捕获,其他变量用值传递捕获。上面的例子中,其等价的表达还有[&, N]
    • [&, M]:指定外部变量M使用值传递捕获(M前面不能加=),其他变量用引用传递捕获。上面的例子中,其等价的表达还有:

【注】:值传递的变量不能修改!!!

1.2 参数列表

就普通函数那样使用,C++14标准之后可以使用auto类型;

2.应用场景

  • 排序:排序算法sort,自定义排序规则的时候需要传入排序函数:

    #include <algorithm>
    #include <iostream>
    #include <vector>
    using namespace std;
    int main(){
      vector<int> vec{0, 11, 3, 19, 22, 7, 1, 5};
      auto rule = [](int a, int b){
        return a < b;
      };
      sort(vec.begin(), vec.end(), rule);
    }
    
  • (还有啥?)

【注】lambda的变量类型如果不用auto,可手动定义为function<返回值类型(变量1类型, 变量2类型)>,例如function<void(string)> lambda = [](string name) {};

posted @ 2023-01-01 22:42  小贼的自由  阅读(88)  评论(0编辑  收藏  举报