• 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;
    }



  • 相关阅读:
    [LeetCode] 852. Peak Index in a Mountain Array
    [LeetCode] 221. Maximal Square
    [LeetCode] 260. Single Number III
    [LeetCode] 532. K-diff Pairs in an Array
    [LeetCode] 1417. Reformat The String
    [LeetCode] 621. Task Scheduler
    [LeetCode] 454. 4Sum II
    [LeetCode] 18. 4Sum
    [LeetCode] 369. Plus One Linked List
    [LeetCode] 380. Insert Delete GetRandom O(1)
  • 原文地址:https://www.cnblogs.com/ye-ming/p/9351042.html
Copyright © 2020-2023  润新知