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]))
#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;
}