C++ 11 標準 新增的Lambda運算式、for_each文法,改變了auto關鍵字的意義

來源:互聯網
上載者:User

  C++ 11標準新增加了Lambda運算式、for_each文法,並改變了auto關鍵字的意義。

  Lambda運算式是一個匿名函數,整個函數體直接內嵌在普通代碼中。

  for_each是C++ 11標準的STL庫中新增加的函數模板,聲明於<algorithm>標頭檔。

  auto關鍵字原先C語言中的意義是自動類型。現在的C++ 11標準新規定把auto關鍵字的意思改成了任意類型,但並不是弱類型,仍然是強型別。auto關鍵字聲明的變數必須初始化,在初始化時候,類型就已經決定了,就是初始化的運算式的傳回值類型。例如代碼 auto n = 1; ,那麼n的類型就被規定成int型了。

  排序代碼:

/* * test.cpp - Lambda運算式、for_each測試 * *   C++ 11標準 Lambda運算式,for_each函數模板 * *             Copyright  葉劍飛  2012 * * *  編譯命令: *        g++ test.cpp -o test -std=c++0x -Wall */#include <iostream>#include <cstdlib>#include <algorithm>   // sort函數模板、for_each函數模板#include <functional>  // function類模板using namespace std;#ifndef _countof#define _countof(_Array) (sizeof(_Array) / sizeof(_Array[0]))#endifint main ( ){    int a[] = {1,2,5,9,52,6,3,14};    function <bool (const int & , const int &)> compare;    auto output = [](int n)->void{ cout << n << endl; };    // C++11標準中, auto 關鍵字新義,任意類型,類型由初始設定式確定    // “[](int n)->void{ cout << n << endl; }”是Lambda運算式    cout << "升序排序" << endl;    compare = []( const int & a , const int & b )->bool { return a < b; };    sort( a, a+_countof(a), compare  );    for_each( a, a+_countof(a), output );    cout << endl;    cout << "降序排序" << endl;    compare = []( const int & a , const int & b )->bool { return b < a; };    sort( a, a+_countof(a), compare  );    for_each( a, a+_countof(a), output );    cout << endl;    return EXIT_SUCCESS;}
相關文章

聯繫我們

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