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';}
阅读全文
0 0
- [c#]: Lambda
- C#-Lambda
- c#Lambda
- c#lambda
- 【c/c++】Lambda表达式
- C#--Lambda表达式
- C++ox 之 lambda
- C#:Lambda 表达式
- C++lambda表达式
- C++lambda表达式
- C++lambda详解~读书笔记
- C# Lambda表达式
- C++:lambda表达式
- C++lambda详解~读书笔记
- C#Lambda表达式
- C++Lambda学习
- 【c++】lambda表达式
- C++lambda表达式简记
- linux下创建mysql用户,并且给增删改查的权限
- Linux 中断学习之前言篇---中断之原理篇
- 【转】C3P0连接池配置——ComboPooledDataSource
- HDU4185 【二分图最大匹配】
- 函数和递归(组合数,孪生素数,用指针实现变量交换,求解二院一次方程组)
- C++ lambda
- vue v-model
- C++学习之路(番外篇)
- 在linux安装JDK
- 保存文件到手机内存
- HDU 1213 How Many Tables 基础并查集★
- 截单返架系统分配货位优化
- 组合数 【nyoj-32】【stl】【dfs】
- Luogu P1563 [NOIP2016]玩具谜题