您的位置:首页 > 其它

Lambda表达式

2016-08-20 11:19 309 查看
在ISO C++11标准中引入了lambda表达式。用于创建并定义匿名的函数对象。以简化编程工作。Lambda表达式的语法如下:

[函数对象参数]
(参数列表)->返回值类型
{函数体};

1.函数对象参数:可以是表达式之前出现过的变量,代表当前Lambda表达式会用到的变量。如果不写这个变量的话,则在Lambda表达式中就无法访问这个变量。如果Lambda需要多个变量的话,则每个变量之间用“,”隔开。如果之前所有的变量都能用到,那么就在[]里面写一个“=”即可。

2.参数列表:当前匿名函数的参数表。

3.返回值类型:当前匿名函数的返回值。

4.函数体:当前匿名函数的函数体。

 
 
举个例子:假如我们有一个数组,我们要对数组当中的元素进行降序排列。最简单的方式就是调用<algorithm>当中的std::sort函数,但是这个函数的第三个参数是一个函数,在C++98标准当中,由于没有Lambda表达式,我们就得这样写:

#include<iostream>
#include<algorithm>
using namespace std;

bool cmp(int a,int b)
{
return a > b;
}

void main()
{
int a[5] = { 1,2,3,4,5 };
cout << "当前数组:";
for (int i = 0; i < 5; i++)
{
cout << a[i] << " ";
}
cout << endl;

sort(a, a + 5, cmp);

cout << "当前数组:";
for (int i = 0; i < 5; i++)
{
cout << a[i] << " ";
}
cout << endl;
system("pause");
}
但是用Lambda表达式的话,我们只需这样写:

#include<iostream>
#include<algorithm>
using namespace std;

void main()
{
int a[5] = { 1,2,3,4,5 };
cout << "当前数组:";
for (int i = 0; i < 5; i++)
{
cout << a[i] << " ";
}
cout << endl;

//不同之处在这里。
sort(a, a + 5, [](int a, int b)->bool{return a > b; });

cout << "当前数组:";
for (int i = 0; i < 5; i++)
{
cout << a[i] << " ";
}
cout << endl;
system("pause");
}
可以看到,使用Lambda表达式可以让代码变得更加简洁。

 

上面已经说到,如果在Lambda表达式当中需要许多参数,那么就将这些参数之间用“,”隔开,下面就举一个这方面的例子:

#include<iostream>
#include<algorithm>
using namespace std;

void main()
{
int num1 = 10;
int num2 = 6;
int a[5] = { 1,2,3,4,5 };

cout << "num1 =" << num1 << "," << "num2 = " << num2 << endl;
cout << "a数组:";
for (int i = 0; i < 5; i++)
{
cout << a[i] << " ";
}
cout << endl;

cout << "将a中每个元素的值都加上(num1+num2)之后:" << endl;
for_each(&a[0], &a[5], [num1, num2](int& x)->void {x += (num1 + num2); });

cout << "a数组:";
for (int i = 0; i < 5; i++)
{
cout << a[i] << " ";
}
cout << endl;
system("pause");
}

如何获取Lambda表达式的返回值?

代码举例:

#include<iostream>
using namespace std;

void main()
{
int(*pFunc)(int, int) = nullptr;//先定义了一个函数指针

pFunc = [](int a, int b)->int {return a + b; };
int num = pFunc(1, 2);
cout << "Lambda表达式的返回值是:" << num << endl;
system("pause");
}

运行结果:

Lambda表达式的返回值是:3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: