C++ 11 標准 新增的Lambda表達式、for_each語法,改變了auto關鍵字的意義


  C++ 11標准新增加了Lambda表達式、for_each語法,並改變了auto關鍵字的意義。

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

  for_eachC++ 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]))
#endif

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM