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

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

  • 相关阅读:
    2010年8月18日周三_Migrating from 1.3 to 2.0_5
    2010年8月12日_周四_UserControlTask control
    2010年8月18日周三_insideTheAPI_overView_6.1
    一个Flex事件的简单的例子
    2010年8月13日_周五_PrintTask control
    如何发布一个GeometryService服务
    lua分割字符串
    lua字符串合并
    lua 类型转换
    linux 下 svn 冲突解决办法
  • 原文地址:https://www.cnblogs.com/sarah-zhang/p/12075687.html
Copyright © 2011-2022 走看看