初级部分
#include<iostream>
using namespace std;
//解决函数嵌套
void main1()
{
[] {cout << "hello world"; }();//hello world limbda表达式
cin.get();
}
void main2()
{
//auto fun = [] {cout << "hello world"; };//这里fun是一个函数指针
//fun();//调用
[] {cout << "hello world"; }();//匿名lambda表达式 最后的()是调用作用
cin.get();
}
void main3()
{
//[] {cout << "hello world", cout << "hello boy"; }();//{}是块语句,函数体,执行
//[](char *str) {cout << str << endl; }("hahaha");
char str[]{ "fangfang" };
auto fun = [](char *str) {cout << str << endl; };
cout << typeid(fun).name() << endl;//class <lambda_...>
//lambda表达式不能直接取地址,无法当做函数指针
fun(str);
cin.get();
}
void main4()
{
auto fun = [](double a, double b) {return a + b; };
cout << fun(10, 19.6) << endl;//29.6
//->在()和{}之间,指定返回值类型
auto fun1 = [](double a, double b)->int {return a + b; };
cout << fun1(10, 19.6) << endl;//29
//内联展开 无法取地址
//decltype类型自动推理
auto fun2 = [](double a, double b)->decltype(a+b) {return a + b; };
cout << fun2(10, 19.6) << endl;
cin.get();
}
void main()
{
int num = 100;
auto fun = [](int num) {num = 5, cout << num << endl; };
fun(num);//5
cout << "main=" << num << endl;//100 并未改变,lambda表达式遵循副本机制
cin.get();
}
深入部分
#include<iostream>
#include<array>
#include<algorithm>//算法
using namespace std;
//主要解决代码内嵌
//[]()->type {}();//匿名表达式
//[],=引用,只读,=mutable,读原本改副本,&读写原本
//()参数,int a,int b
//{}语句的实现 ()调用
//->指定返回值类型
void mainA()
{
int num1 = 111;
int num2 = 222;
//[]() {cout << num1 << num2 << endl; }();//报错
[=]() {cout << num1 << num2 << endl; }();//[=]捕获外部变量
//[=]() {num1=20,num2=30,cout << num1 << num2 << endl; }();//报错,[=]只可以读外部变量
[=]()mutable {num1 = 10, num2 = 30, cout << num1 << num2 << endl; }();//mutable修改副本
cout << "main= " << num1 << " " << num2 << endl;//111 222
[&]() {num1=10,num2=30,cout << num1 << num2 << endl; }();//[&]读写外部变量
cout << "main1= " << num1 << " " << num2 << endl;//10 30
cin.get();
}
void mainB()
{
//混合机制
int a = 10;
int b = 9;
int c = 8;
[&a,b,c]() {a=111,cout << a << b << c << endl; }();//只有a可读可写
cin.get();
}
void mainC()
{
[](auto a, auto b) {cout << a + b << endl; }(10, 11);
[](auto a=0, auto b=0) {cout << a + b << endl; }(10, 11);//附初始值只能=不能()
[](int a = 2, int b = 4) {cout << a + b << endl; }();//6 用auto的话不确定类型
cin.get();
}
void main()
{
array<int, 10>myint{ 0,1,2,3,4,5,6,7,8,9 };
for_each(myint.begin(), myint.end(), [](int num) {cout << num << endl; });//显示
for_each(myint.begin(), myint.end(), [](int &num) {num+=1,cout << num << endl; });//修改,所有元素+1
for_each(myint.begin(), myint.end(), [](int num) {cout << num << endl; });//被改变
cin.get();
}