c++ Lambda表达式

[capture list] (params list) mutable exception-> return type { function body }            

表达式中各个参数的含义如下:
[capture list]:外部变量列表         (表示外部传进来的数值)
(params list):形参列表             (比如用for_each传进来的数值)
mutable:表示能不能修改捕获的变量     (可省略)
exception:异常设定                  (可省略)         
return type:返回类型                (可省略)
function body:函数体     

#include <iostream>
#include <vector>
#include <set>
#include <algorithm>

using namespace std;

void myPrintf(int elem)
{
	cout << elem << " ";
}

int main()
{
	vector<int> vec(5);
	int i = 1;
	int num = 0;
	cout << "-----------通过外部参数给vec赋值,num改变,i不改变----------" << endl;
	generate(vec.begin(), vec.end(), [i, &num]() {
		num = i * i + num;
		return num;
	});
	cout << "-----------值传递和引用传递的区别----------" << endl;
	cout << "i = " << i << "  num = " << num << endl;
	cout << "-----------打印vec中的值----------" << endl;
	for_each(vec.begin(), vec.end(), [](int i) {
		cout << i<<" "; 
	});
	cout << endl;

	cout << "-----------传递外部变量和形参,引用传递则改变外部变量----------" << endl;
	int total = 0;
	for_each(vec.begin(), vec.end(), [&total](int i) {
		total += i;
	});
	cout << "total = " << total << endl;

	cout << "-----------形参以值传递方式,实参的数值不改变----------" << endl;
	int num1 = 10;
	int num2 = 5;
	for_each(vec.begin(), vec.end(), [=](int x) {
		x = x * num1 + num2;
		cout << "x = " << x << endl;
	});
	//vec中的数值未改变
	for_each(vec.begin(), vec.end(), myPrintf);//可用myPrintf函数来打印输出,也可用lambda来打印
	cout << endl;
	cout << "-----------形参以引用传递方式,实参的数值会改变----------" << endl;
	for_each(vec.begin(), vec.end(), [=](int &x) {
		x = x * num1 + num2;
		cout << "x = " << x << endl;
	});
	//vec中的数值改变
	for_each(vec.begin(), vec.end(), myPrintf);
	cout << endl;

	cout << "-----------删除digits中等于blacklist的数值----------" << endl;
	std::set<int> blacklist = { 7, 8, 9 };
	std::vector<int> digits = { 3, 9, 1, 8, 4, 7, 1 };
	digits.erase(std::remove_if(digits.begin(), digits.end(), [blacklist](int i) {
		return blacklist.find(i) != blacklist.end();
	}),
		digits.end());
	for (auto i : digits)
		cout << i << endl;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值