C++11之Lambda

版权声明:guojawee https://blog.csdn.net/weixin_36750623/article/details/84860652

Lambda表达式的语法通过下图来介绍:
在这里插入图片描述
① [ ]中的=、&分别表示传递参数时以值传递、引用传递
② 形参列表
③ Mutable 标识
④ 异常标识
⑤ 返回值类型:使用C++11新增的返回类型后置语法
⑥ 函数体,也就是lambda表达式需要进行的实际操作


1、函数指针、仿函数、Lambda都称为函数对象
① 因为Lamda是函数对象,因此可以给Lambda表达式重命名,如:

//x能整出y,返回true
auto Lmd = [](int x, int y)->bool{return (x % y) == 0; };

② 因为Lamda是函数对象,因此它能像函数那样被调用。(可以将Lambda看成是函数名)

bool flag = Lmd(10, 3); //flag = false;

int cnt = std::count_if(vec.begin(), vec.end(), 
		[](int x)->bool{return x > 0;}
	);

③ 因为Lamda是函数对象,因此它能被bind进行适配,例:

auto Lmd = [](int x, int y)->bool{return (x % y) == 0; };
atuo Lmd_2 = std::bind(Lmd, _1, 2); //绑定Lambda表达式的第2参数为2
atuo Lmd_5 = std::bind(Lmd, 5, _1); //绑定Lambda表达式的第1参数为5

2、[ ]中的=、&分别表示传递参数时以值传递、引用传递
统计vec中能整除3的元素的总个数

//cnt1传递的是引用,被修改
int main(){
	int cnt1 = 0;
	for_each(vec.begin(), vec.end(),
		[&cnt1](int x)->void{if (x % 3 == 0) cnt1++;} 
	);

//&cnt3 、 =div
	int cnt2 = 0;
	int div = 2; //被除数
	for_each(vec.begin(), vec.end(),
		[&cnt2, div](int x)->void{if (x % div == 0) cnt2++; }
	);

	int cnt3 = 0;
	for_each(vec.begin(), vec.end(),
		std::bind([&cnt3](int x, int div)->void{if (x % div == 0) cnt3++; }, _1, 2) //bind被除数=2
	);
}

猜你喜欢

转载自blog.csdn.net/weixin_36750623/article/details/84860652