c++11 Lambda浅显实战理解

本文探讨了C++11 Lambda表达式的使用,展示了如何通过简化函数调用提升代码简洁性,并介绍如何利用Lambda重用表达式解决重复问题。通过实例演示,阐述了Lambda在优化大型项目代码结构上的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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


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


int main()
{
	int count = 0;
	vector<int>numbers(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 <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;


int main()
{
	int count = 0;
	vector<int>numbers(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 <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;


int main()
{
	int count = 0;
	vector<int>numbers(20);
	vector<int> 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值