码迷,mamicode.com
首页 > 编程语言 > 详细

C++ lambda表达式 (二)

时间:2018-07-22 19:19:53      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:init   ssi   cap   its   style   function   表达式   element   algo   

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

 

C++ lambda表达式 (二)

标签:init   ssi   cap   its   style   function   表达式   element   algo   

原文地址:https://www.cnblogs.com/ye-ming/p/9351042.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!