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

相关文章:

  • 2021-12-17
  • 2021-08-17
  • 2021-09-13
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2020-05-30
  • 2022-03-07
  • 2022-01-17
  • 2021-10-18
  • 2021-08-08
  • 2021-06-24
相关资源
相似解决方案