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



  • 相关阅读:
    配置sonar、jenkins进行持续审查
    maven命令解释
    Maven中-DskipTests和-Dmaven.test.skip=true的区别
    maven之一:maven安装和eclipse集成
    Eclipse安装Maven插件
    IntelliJ IDEA单元测试和代码覆盖率图解
    关于Spring中的<context:annotation-config/>配置
    Java开发之@PostConstruct和@PreConstruct注解
    Java定时任务的三种实现方法
    JAVA之Mybatis基础入门二 -- 新增、更新、删除
  • 原文地址:https://www.cnblogs.com/ye-ming/p/9351042.html
Copyright © 2020-2023  润新知