C++中的Lambda表达式

C++中的Lambda表达式

基本表达格式:

[captureList] (parameterList) -> returnType {function body}
一、捕获(capture)
1、值捕获(capture by value)

值捕获的变量在Lambda表达式定义时就已经确定

例子:
# include <iostream>
using namespace std;

int main(){
    int x = 5;
    auto f = [x] (int y) -> int {return x+y;};
    x = 50;
    cout << f(5) << endl;
    return 0; 
}

结果

10
2、引用捕获(capture by reference)

在Lambda函数定义时,捕获变量前面加上&,表示捕获对应变量的内存地址,这样捕获变量的值在函数调用时才会确定

# include <iostream>
using namespace std;

int main(){
    int x = 5;
    auto f = [&x] (int y) -> int {return x+y;};
    x = 50;
    cout << f(5) << endl;
    return 0; 
}

结果

55
3、隐式捕获(implict capture)

在捕获变量中不使用具体的变量名,而只使用=或者&,表示捕获函数所需的所有外部变量的值或引用,这样可以避免遗漏。

只使用=
# include <iostream>
using namespace std;

int main(){
    int x = 5;
    int y = 10;
    auto f = [=] (int z) -> int {return x+y+z;};
    x = 50;
    y = 100;
    cout << "f(5)=" << f(5) << endl;
    return 0;
}

结果

f(5)=20
只使用&
# include <iostream>
using namespace std;

int main(){
    int x = 5;
    int y = 10;
    auto f = [&] (int z) -> int {return x+y+z;};
    x = 50;
    y = 100;
    cout << "f(5)=" << f(5) << endl;
    return 0;
}

结果

f(5)=155

注意:不能同时使用=和&,因为这样会造成冲突,导致函数无法理解到底是捕获值还是捕获引用,编译也会报错

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值