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