#include <iostream>
#include <vector>
#include <stdlib.h>
#include <algorithm>
#include <time.h>
using namespace std;
void fun1()
{
vector<int> vi;
for(int i = 0; i<10; i++)
vi.push_back(rand()%100);
sort(vi.begin(),vi.end(), [](int x,int y){return x<y;}); // 无返回值,自动传参;
while(!vi.empty())
{
cout << vi.back() << " ";
vi.pop_back();
}
cout << endl;
}
void fun2()
{
float b = -3.5;
cout << [](float a){ return abs(a);}(b) << endl; // 自动推断返值类型,手动传参
}
void fun3()
{
float f = 3.5;
cout << [](float a)->int{return abs(a);}(f) << endl;// 手动设置反值类型 ->int
}
void fun4()
{
int a = 1;
cout << [=](int b){return a+b;}(1)<< endl;//= 表示值传递,变量a使用相同作用于内的变量,如果没有=,就会报错,找不到a。
cout << a << endl;
}
void fun5()
{
int a = 1;
cout << [=](int b)mutable{return a+=b;}(1) << endl;//a的值不能修改( 如果没有mutable就会报错)
cout << a << endl;// 即便在上面修改了,a还是以前的值
}
void fun6()
{
int a = 1;
cout << [&](int b){return a+b;}(1) << endl;
cout << a << endl;
}
void fun7()
{
int a = 1;
cout << [&](int b){return a+=b;}(1) << endl;
cout << a << endl;
}
void fun8() //混合使用
{ //[] // 不捕获任何外部变量
int a = 1; //[=] // 以值的形式捕获所有外部变量
int b = 1; //[&] // 以引用形式捕获所有外部变量
cout << [=,&b](int c){return b+=a+c;}(1)<< endl; //[x, &y] // x 以传值形式捕获,y 以引用形式捕获
cout << b << endl; //[=, &z]// z 以引用形式捕获,其余变量以传值形式捕获
} //[&, x] // x 以值的形式捕获,其余变量以引用形式捕获
int main()
{
srand(time(NULL));
fun8();
int val = 10;
auto lambda = [=] () -> int { return val * 100; };
cout << lambda() << endl;
return 0;
}
// auto lambda = [=] () -> int { return val * 100; };
// std::function<int()> lambda = [] () -> int { return val * 100; };与上面的效果是一样的,可以直接像函数调用一样使用