栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++11 Lambda浅显实战理解

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++11 Lambda浅显实战理解

c++11 Lambda表达式
先看一个使用Lambda和不使用Lambda的区别
例:

#include 
#include 
#include 
#include 
using namespace std;


bool f3(int x)
{
	return x % 3 == 0;
}


int main()
{
	int count = 0;
	vectornumbers(20);
	generate(numbers.begin(), numbers.end(), rand);


	count = count_if(numbers.begin(), numbers.end(), f3);

	cout << count << endl;
	return 0;
}

从这一段代码中可以看到,首先初始化一个数组。然后填充随机数。通过调用f3函数获取多少数字能被3整除。很显然,这里面设计到了调用其他的函数f3。如果是在大型项目中,这样的调用可能相隔十万八千行。十分影响阅读代码的效率。而Lambda则很好的规避了这个问题。代码如下

```cpp
#include 
#include 
#include 
#include 
using namespace std;


int main()
{
	int count = 0;
	vectornumbers(20);
	generate(numbers.begin(), numbers.end(), rand);


	count = count_if(numbers.begin(), numbers.end(), [](int x) {return x % 3 == 0;});

	cout << count << endl;
	return 0;
}

这里对函数的调用进行了优化,在count计算时,直接用lambda表达式进行了替换。这里就优化了代码的简洁性和可读性。然而当一个Lambda表达式需要实用两次时,每次书写同一个会十分的不方便,在此c++11也进行了优化。代码如下

#include 
#include 
#include 
#include 
using namespace std;


int main()
{
	int count = 0;
	vectornumbers(20);
	vector n2(30);
	generate(numbers.begin(), numbers.end(), rand);
	generate(n2.begin(), n2.end(), rand);

	auto mod = [](int x) {return x % 3 == 0;};
	count = count_if(numbers.begin(), numbers.end(), mod);
	int count2 = count_if(n2.begin(), n2.end(), mod);

	return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/458177.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号