C++ lambda運算式 (二)

來源:互聯網
上載者:User

標籤: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運算式 (二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.