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

原文链接: https://www.cnblogs.com/yejianfei/archive/2012/10/18/2730152.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/66202

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午12:13
下一篇 2023年2月9日 下午12:13

相关推荐