#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;
}
#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;
}