C++ 11 标准 Lambda表达式

  C++ 11标准新增加了Lambda表达式,以后小函数可以直接内嵌Lambda表达式搞定了。例如排序,我们以前要这么写:

#include <iostream>
#include <cstdlib>
#include <algorithm>

bool compare( const int & a, const int & b )
{
    return a < b;
}

using namespace std;

int main ( )
{
    int a[10] = {5,1,2,3,6,9,8,2,3,6};
    sort( a, a+9, compare );
    for ( int i = 0 ; i < 9 ; i ++ )
        cout << a[i] << endl;
    return EXIT_SUCCESS;
}

  用C++ 11标准的Lambda表达式,这么写就行了:

#include <iostream>
#include <cstdlib>
#include <algorithm>

using namespace std;

int main ( )
{
    int a[10] = {5,1,2,3,6,9,8,2,3,6};
    sort( a, a+9, []( const int & a, const int & b )->bool{ return a < b; } );
    for ( int i = 0 ; i < 9 ; i ++ )
        cout << a[i] << endl;
    return EXIT_SUCCESS;
}
posted @ 2012-10-18 21:36  叶剑飞Victor  阅读(557)  评论(0编辑  收藏  举报