C++ lambda

来源:互联网 发布:第三方数据平台 编辑:程序博客网 时间:2024/05/21 04:21

参考stackoverflow、 cppreference

声明

[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';}
原创粉丝点击