C++ lambda表达式 (二)

时间:2021-01-23 19:11:18
#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;
}

  

 

C++ lambda表达式 (二)

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

C++ lambda表达式 (二)

 

 

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