c++ lambda学习

一. 书写形式

[ capture clause ] (parameters) -> return-type { definition of method }

[ 捕获 ] ( 参数列表 ) -> 返回类型 { 函数定义 }
return-type返回值一般可以推导出来, 可以不用写, 所以可以简化为
[ capture clause ] (parameters) { definition of method }
但是在一些复杂的情况下, 比如条件语句这种, return-type是不能省略的

几个用例

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

void print_vector(vector<int> v)
{
	for_each(v.begin(), v.end(), [](int i) {
		cout << i << " ";
	});
	cout << endl;
}

int main() {

	vector<int> v{ 4, 1, 3, 5, 2, 3, 1, 7 };
	print_vector(v);

	// 首个比4大的数字
	vector<int>::iterator p = find_if(v.begin(), v.end(), [](int i) {
		return i > 4;
	});
	cout << "first number greater than 4 is " << *p << endl;

	// 排序
	sort(v.begin(), v.end(), [](const int& a, const int& b) {
		return a > b;
	});
	print_vector(v);

	// 大于等于5的数字的个数
	int bigger_than_5_number = count_if(v.begin(), v.end(), [](int a) {
		return a >= 5;
	});
	cout << "the number of elements greater than or equal 5 is: " << bigger_than_5_number << endl;

	// 去重
	vector<int>::iterator p2 = unique(v.begin(), v.end(), [](int a, int b) {return a == b;});
	v.resize(distance(v.begin(), p2));
	print_vector(v);

	int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	// 阶乘
	int res = accumulate(arr, arr + 10, 1, [](int a, int b) {
		return a * b;
	});

	// 平方
	auto square = [](int i) {
		return i * i;
	};
	cout << "square of 5 is : " << square(5) << endl;
}

执行结果
在这里插入图片描述

二. 详解捕获

lambda表达式还能够从闭包中获取数据, 就是[]中声明的
[a]: 不写&=的话, 默认值捕获
有三种方式:
[&] : 通过引用捕获所有外部变量
[=] : 通过值捕获所有外部变量
[a, &b] : a通过值捕获, b通过引用捕获

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


int main() {

	vector<int> v1 = { 3, 1, 7, 9 };
	vector<int> v2 = { 10, 2, 7, 16, 9 };

	auto push_number = [&](int a) {
		v1.push_back(a);
		v2.push_back(a);
	};
	push_number(20);

	auto print_v1 = [v1]() {
		for (auto p = v1.begin(); p != v1.end(); p++)
			cout << *p << " ";
		cout << endl;
	};
	print_v1();


	int N = 5;
	// 首个比N大的数
	vector<int>::iterator p = find_if(v1.begin(), v1.end(), [N](int i) {
		return i > N;
	});
	cout << "first number greater than 5 is " << *p << endl;

	// 大于等于5的数
	int count_n = count_if(v1.begin(), v1.end(), [=](int i) {
		return i >= N;
	});
	cout << "the number of elements greater than or equal 5 is " << count_n << endl;
}

执行结果
在这里插入图片描述

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值