C++ lambda表达式的几个例子

统计一个vector中奇偶数的个数:

lambda做法:这样就避免了再多定义统计函数,简洁了不少

template<typename U>    //要使用模板,因为返回值可能会多样
int Counter(vector<int>& numberVec, U filter) {
	int count = 0;
	for (auto& x : numberVec) {
		if (filter(x) == 1) {
			count++;
		}
	}
	return count;
}
//过滤函数的使用 奇数


//统计函数
int CountOdds(vector<int>& numberVec) {
	return Counter(numberVec, [](int x) {return x % 2 != 0; });
}

int CountEvens(vector<int>& numberVec) {
	return Counter(numberVec, [](int x) {return x % 2 == 0; });
}

统计vector中大于某个数的数的个数:

template<typename U>
int GreatCounter(vector<int>& numberVec, U filter) {
	int count = 0;
	for (auto& x : numberVec) {
		if (filter(x) == 1) {
			count++;
		}
	}
	return count;
}
	

int counterGreater(vector<int>& numberVec, int y) {
	return GreatCounter(numberVec, [=](int x) {return x > y; });    //返回的是bool类型
}

把A中的数值倒序排序后复制到B中

template<typename U>   //遍历处理函数
void travers(vector<int>& numberVec, U process) {
	for (auto& x : numberVec) {
		process(x);
	}
}

void theCopyFunction(vector<int>& a,vector<int>& b, int y) {
	
	travers(a, [&, y](int x) {
		if (x > y) {
			b.push_back(x);
		 }
	}
	);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值