C++学习_lambda表达式_八

lambda表达式

很多语言都有增加了lambda表达式,我没想到c++也增加了,lambda表达式是一个不错的语法糖

基本结构

[] () mutable throw() -> int 
{
    
    
}

捕获子句[]

这个东西是用来捕获外部变量的

不捕获任何变量

#include <iostream>
#include <string>

using namespace std;

int main() {
    int a = 123;
    auto func = []() {
        cout << "hello lambda exp";
    };
    func();
    return 0;
}

捕获一个变量

#include <iostream>
#include <string>

using namespace std;

int main() {
    int a = 123;
    auto func = [a]() {
        cout << a;
    };
    func();
    return 0;
}

捕获所有变量的拷贝

拷贝就说明变量在表达式内部只可读而不可更改(即使更改,这个更改也不会传递到外部),当然值传递只能捕获在lambda函数之前的变量

#include <iostream>
#include <string>

using namespace std;

int main() {
    int a = 123;
    int b = 456;
    string c = "tinuv";
    auto func = [ = ]() {
        cout << a << "\n";
        cout << b << "\n";
        cout << c << "\n";
        cout << d;
    };
    func();
    return 0;
}

引用捕获

#include <iostream>
#include <string>

using namespace std;

int main() {
    int a = 123;
    int b = 456;
    auto func = [ &a, &b ]() {
        cout << a << "\n";
        cout << b << "\n";
        b = 10;
    };
    a = 678;
    func();
    cout << b;
    return 0;
}

输出结果是

678
456
10

除此之外还可以捕获this指针,这主要在面向对象中使用,这里不介绍

mutable关键字

如果不使用mutable关键字的话,修改值传递的变量是会报错的,但如果使用mutable关键字的话就可以更改值传递的变量了,但是,即使修改了也==不能传递到外部==

#include <iostream>
#include <string>

using namespace std;

int main() {
    int a = 123;
    int b = 456;
    auto func = [a, b]()mutable {
        cout << a << "\n";
        cout << b << "\n";
        b = 10;
        cout << b << "\n";
    };
    func();
    cout << b;
    return 0;
}

throw()子句

这里暂时不介绍

参数列表,返回类型,函数主体

都跟其他语言的差不多,就不多说了

??正文结束??
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值