zoukankan      html  css  js  c++  java
  • C++ lambda表达式 (二)

    #include <functional>
    #include <iostream>
    
    int main()
    {
       using namespace std;
    
       int i = 3;
       int j = 5;
    
       // The following lambda expression captures i by value and
       // j by reference.
       function<int (void)> f = [i, &j] { return i + j; };
    
       // Change the values of i and j.
       i = 22;
       j = 44;
    
       // Call f and print its result.
       cout << f() << endl;
    }
    

      

    可以看到i是拷贝值,j是引用值,所以是24,结果26

    • 把lambda表达式当作参数传送

    #include <list>
    #include <algorithm>
    #include <iostream>
    int main()
    {
        using namespace std;
        // Create a list of integers with a few initial elements.
        list<int> numbers;
        numbers.push_back(13);
        numbers.push_back(17);
        numbers.push_back(42);
        numbers.push_back(46);
        numbers.push_back(99);
    
        // Use the find_if function and a lambda expression to find the 
        // first even number in the list.
        const list<int>::const_iterator result = 
            find_if(numbers.begin(), numbers.end(),[](int n) { return (n % 2) == 0; });//查找第一个偶数
    
        // Print the result.
        if (result != numbers.end())
         {
            cout << "The first even number in the list is " << *result << "." << endl;
        } else 
        {
            cout << "The list contains no even numbers." << endl;
        }
    }
    • lambda表达式嵌套使用 

    #include <iostream>
    
    int main()
    {
        using namespace std;
    
        // The following lambda expression contains a nested lambda
        // expression.
        int timestwoplusthree = [](int x) { return [](int y) { return y * 2; }(x) + 3; }(5);
    
        // Print the result.
        cout << timestwoplusthree << endl;
    }
    • ambda表达式使用在高阶函数里

    #include <iostream>
    #include <functional>
    
    int main()
    {
        using namespace std;
    
        auto addtwointegers = [](int x) -> function<int(int)> { 
            return [=](int y) { return x + y; }; 
        };
    
        auto higherorder = [](const function<int(int)>& f, int z) { 
            return f(z) * 2; 
        };
    
        // Call the lambda expression that is bound to higherorder. 
        auto answer = higherorder(addtwointegers(7), 8);
    
        // Print the result, which is (7+8)*2.
        cout << answer << endl;
    }



  • 相关阅读:
    Displaying Tabbed and Stacked Canvas Using Show_View In Oracle Forms
    Sort Detail Data Block Example
    Oracle Forms Execute_Query Example To Fetch The Records From Database
    web交互方式
    Ajax、Comet与Websocket
    Websocket和PHP Socket编程
    websocket webworker
    Android消息推送
    游戏服务器
    Comet:基于 HTTP 长连接的“服务器推”技术
  • 原文地址:https://www.cnblogs.com/ye-ming/p/9351042.html
Copyright © 2011-2022 走看看