lambda modern C++

來源:互聯網
上載者:User

標籤:syntax   param   poi   def   reference   ams   int   bsp   apr   

Lambda expressions (since C++11)Syntax
 
[ captures ] <tparams>(optional)(c++20) ( params ) specifiers(optional) exception attr -> ret { body } (1)  
 
[ captures ] ( params ) -> ret { body } (2)  
 
[ captures ] ( params ) { body } (3)  
 
[ captures ] { body } (4)  
 

上代碼:

 1 // lambdaprj.cpp : Defines the entry point for the console application. 2 // 3  4 #include "stdafx.h" 5 #include<algorithm> 6 #include<vector> 7 #include<iostream> 8 #include<functional> 9 using namespace std;10 11 /*12 *    []()->{};  13 *    [ capture list] ( params list) mutable exception attribute -> ret { body }14 */  15 int main()16 {17     auto sayHelloWorld = []() {18         cout << "hello world" << endl;19     };20     sayHelloWorld();21     auto add_ = [](int a,int b)->int {22         return a + b;23     };24     cout<< add_(190, 10)<<endl;25 26     int i = 99;//read only27     auto add_with_i = [i](int a, int b)->int {28         return a + b + i;29     };30     cout << add_with_i(190,10)<<endl;31     //32 33     int j = 100;34     auto add_with_j_c = [&j](int a, int b)-> int{35         j = 101;36         return a + b + j;37     };38     cout << add_with_j_c(190, 10) << " j:" << j << endl; 39     //40 41     vector<int> arr = { 1,2,3,4,5 };42     int total = 0;43     for_each(begin(arr), end(arr),44         [&](int x)->int{45         return total += x;46     });47     cout << "total:" << total << endl;48     //49     vector<int> sort_arr = { 2,-1,3,4,6,7,2,31 };50     cout << "unsort : ";51     for_each(begin(sort_arr),end(sort_arr),52         [](int x) {53         cout << x << " "; });54     cout << endl;55     sort(begin(sort_arr),end(sort_arr),56         [](int a, int b)->bool {57         return abs(a) < abs(b); });58     cout << "sort   : ";59     for_each(begin(sort_arr), end(sort_arr),60         [](int x) {61         cout << x << " "; });62     cout << endl;63     //64 65     auto func = [](function<void()> f) {66         f();67     };68     int x = 100;69     auto func_add = [&]() {70         x++;71     };72     func(func_add);73     cout << "x:" << x << endl;74     getchar();75     return 0;76 }

 

參考學習:

1、https://www.youtube.com/watch?v=uk0Ytomv0wY

2、http://en.cppreference.com/w/cpp/language/lambda

lambda modern C++

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.