C++ lambda表达式复习

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


int main()
{
//最简单的lambda表达式
[](){};
//lambda表达式也就是一个函数,我们可以把它赋给函数指针,也可以在后面加上括号使用。
//
//[]里面可以添加一些限制lambda块语句中使用外部变量的限制符。一共有四种情况:
//1.空白表示不能对外部变量进行读写。
//2.=表示可以对外部变量进行读访问。
//3.&表示可以对外部变量进行读写访问。
//4.可以同时填写&变量名或不加&的变量名,加了&的变量可以进行读写,不加&的变量只能进行读访问。
//
//()里面是函数的参数。
//
//{}里面是函数的表达式。


//例一:将lambda表达式赋予函数指针
void(*p)(int);
p = [](int num){ cout << num << endl; };
p(1);


//例二:将lambda表达式用作函数
[](int num){cout << num << endl; };
[](int num){cout << num << endl; }(1);


//例三:对外部变量进行访问
int temp1 = 10, temp2 = 20;
//auto tempa = [=](){cout << temp1 << endl << temp2 << endl; };//此时只能对temp1和temp2进行读访问。
//tempa();
//auto tempb = [&](){temp1 = 20; temp2 = 10; cout << temp1 << endl << temp2 << endl; };//此时可以对temp1和temp2进行读写访问,注意:此时读写的变量为原本变量。
//tempb();
//auto tempc = [&temp1, temp2](){temp1 = 30; cout << temp1 << endl << temp2 << endl; };//此时可以对temp1进行读写访问,但是只能对temp2进行读访问。
//tempc();
//auto tempd = [=]()mutable{temp1 = 20; temp2 = 10; cout << temp1 << endl << temp2 << endl; };//此时可以对temp1和temp2进行读写访问,但是temp1和temp2是原来变量的副本。


/*
lambda表达式可以允许在函数内再次定义函数(匿名函数),lambda表达式对数据结构的遍历格外好用。
*/


//例四:用lambda表达式对数组进行访问
int arr1[5] = { 1, 2, 3, 4, 5 };
for_each(arr1, arr1 + 5, [](int num){cout << num << endl; });


array<int, 5> arr2 = { 1, 2, 3, 4, 5 };
for_each(arr2.begin(), arr2.end(), [](int num){cout << num << endl; });


cin.get();
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值