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

猜你喜欢

转载自www.cnblogs.com/ye-ming/p/9351042.html