C++Lambda表达式

C++11引入的Lambda表达式可以快速的得到某些只调用1次的函数,可以理解成匿名函数,方便阅读时直接了解到调用函数的功能。
注意在例如cb、dev中编译设置要有-stdc++11,因为这是11的标准,这个表达式可以结合着auto一起用

实验Code

#include <bits/stdc++.h>
using namespace std;

//lambda表达式
//匿名函数

class test
{
public:
    void hello() {
        cout << "test hello\n";
    };
    void lambda() {
        auto fun = [this]{ // 捕获了 this 指针
            this->hello(); // 这里 this 调用的就是 class test 的对象了
        };
        fun();
    }
};

int main() {
//example_1
  int arr[10] = {1,2,3,4,5,6,7,8,9,10};
  int sum = 0;
  for (int i = 0; i < 10; i++) {
    sum += [](int n) {return n%2?n:0;}(arr[i]);
  }
  printf("%d\n\n", sum);

//example_2
  float f = -3.5;
  cout << [](float f){return fabs(f);}(f) << endl;
  cout << [](float d)->int{return fabs(d);}(f) << endl; //指定返回值类型
  cout <<endl;

//example_3
  int i = 2, j = 3;
  cout << "external = " << &i << endl;
  cout << "external = " << i << endl;
  cout << "external = " << &j <<endl;
  cout << "external = " << j << endl;
  cout << endl;
  auto p = [=, &i]{
    cout << "internal = " << &i << endl;
    cout << "internal = " << i << endl;
    cout << "internal = " << &j <<endl;
    cout << "internal = " << j << endl;
    cout <<endl;
  };
  p(); //调用方法1  类似于函数指针
  [=]{
    cout << "internal = " << &i << endl;
    cout << "internal = " << i << endl;
    cout << "internal = " << &j <<endl;
    cout << "internal = " << j << endl;
    cout << endl;
  }();//调用方法2  一次匿名函数
  [i,&j]{
    cout << "internal = " << &i << endl;
    cout << "internal = " << i << endl;
    cout << "internal = " << &j <<endl;
    cout << "internal = " << j << endl;
    cout << endl;
  }();//指定拷贝、引用

//example_4
    test t;
    t.lambda(); //this捕获

  return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小胡同的诗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值