zoukankan      html  css  js  c++  java
  • C++, lambda function/expression

    0. lambda emerged since c++11, lambda expression/function is an unnamed function object capable of capturing variables in scope.

    A lambda function is a function that you can write inline in your source code (usually to pass in to another function, similar to the idea of a function pointer). 

    1. syntax of a lambda expression

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

    [ captures ] ( params ) -> ret { body }

    [ captures ] ( params ) { body }

    [ captures ] { body } 

    2. Examples:

    [](){};   // barebone lambda, [] is the capture list, ()is the argument list, {} is the function body

    [](){}(); // immediately execute a lambda or call the lambda function

    auto pr = [](int& n){n = n+1; std::cout << " " << n;};  // define a lambda function, and assign it to the pr

    #include <algorithm>  // std::for_each()

    std::for_each(v.begin(), v.end(), pr); // caller of the lambda expression

    std::for_each(v.begin(), v.end(), [](int &n){ n++; std::cout << " " << n; }); // the same lambda function caller 

    3. About capture list

    [] Capture nothing
    [&] Capture any reference variable by reference
    [=] Capture any reference variable by making a copy
    [=, &foo] Capture any referenced variable by making a copy, but capture variable foo by reference
    [bar]  
    [this]  

     

     

    int x = 4; 

    auto y = [&r = x, x = x+1]()->int{ r += 2; return x+2;}(); //::x will be 6, y will be 7;

    or

    auto y = [&r = x, x = x+1]()->int{ r += 2; return x+2;}; // it is not excuted now 

    y(); // it is executed. ::x is 6

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

  • 相关阅读:
    JdbcTemplate增删改查案例
    顾问和注解
    使用多种方式实现AOP
    面试题
    Spring Bean的生命周期和作用域
    IOC和AOP交互拓展(二)
    AOP
    错题
    Spring核心概念
    hadoop-MapReduce框架原理之OutputFormat数据输出
  • 原文地址:https://www.cnblogs.com/sarah-zhang/p/12075687.html
Copyright © 2011-2022 走看看