C++ lambda

参考stackoverflowcppreference

声明

[captures](optional)(c++20) ( params ) specifiers(optional) exception attr -> ret { body }

例子:

//ret operator()(params) {body}
auto sum = [](int a, int b) { return a + b;};
//template<template-params>
//ret operator()(params) { body }
auto smaller = []<class T>(T a, auto&& b) {return a < b;};

参数

captures: 用来操作**非**lambda函数传入参数(params)的变量

​ a comma-separated list of zero or more captures, optionally beginning with a capture-default.Capture list can be passed as follows (see below for the detailed description):

  • [a,&b] where a is captured by copy and b is captured by reference.
  • [this] captures the current object (*this) by reference
  • [&] captures all automatic variables used in the body of the lambda by reference and current object by reference if exists
  • [=] captures all automatic variables used in the body of the lambda by copy and current object by reference if exists
  • [] captures nothing

例子:

int main(){
    // a没有传进函数f和g,通过capture在lambda函数中使用
    int a = 5;

    // same as: auto f = [&](int b){...}
    auto f = [&a](int b){ 
        a = a + b;
        return a;
    };

    auto g = [=](int b) mutable{ 
        a = a + b;
        return a;
    };
    cout << g(3) << endl; // 8
    cout << a << endl; // 5, by copy, don't change a's value
    cout << f(3) << endl; // 8
    cout << a << endl; // 8

    // [&a], capture a by reference
    // [&, a], capture all automatic variables used in lambda body by reference default 
    // while capture `a` by copy
    // [=, &a], capture all by copy default, capture `a` by reference
    return 0;
}

常见使用案例:最主要的使用是和stl库相结合使用。

#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>

int main()
{
    std::vector<int> c = {1, 2, 3, 4, 5, 6, 7};
    int x = 5;
    c.erase(std::remove_if(c.begin(), c.end(), [x](int n) { return n < x; }), c.end());

    std::cout << "c: ";
    std::for_each(c.begin(), c.end(), [](int i){ std::cout << i << ' '; });
    std::cout << '\n';

    // the type of a closure cannot be named, but can be inferred with auto
    auto func1 = [](int i) { return i + 4; };
    std::cout << "func1: " << func1(6) << '\n';

    // like all callable objects, closures can be captured in std::function
    // (this may incur unnecessary overhead)
    std::function<int(int)> func2 = [](int i) { return i + 4; };
    std::cout << "func2: " << func2(6) << '\n';
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值