一、lambda函数
main.cpp
#include <iostream>
#include "template.h"
using namespace std;
int main()
{
auto f5 = [](int a) ->int {
return a + 1;
};
f5(1);
vector<int> myvector = { 10, 20, 30, 40, 50 };
int isum = 0;
for_each(
myvector.begin(), myvector.end(), [&isum](int val) {//&isum传递是外部isum的引用可以被赋值
isum += val;
cout << val << endl;//依次返回10,20,30,40,50
}
);
cout << isum << endl;
int x = 5;
auto f6 = [=]
{
return x;//=传递是外部所有变量的值,只能调用,不能被赋值,而且已经被赋值为5,后面改变也没有用
};
x = 10;
cout << f6() << endl; //输出为5
int x1 = 5
auto f7 = [&]
{
return x;//&传递是外部所有变量的引用,后面的修改有效,修改为10
};
x1 = 10;
cout << f7() << endl; //输出为10
}
[捕获外部变量](形式参数) ->返回值
{函数体}
形式参数如果没有可以省略,返回值如果没有可以省略,如果不需要捕获外部变量,可以为空。最简单的式子如下:
auto f = []{return 1};
lamdba就是匿名函数。
二、类成员函数 lambda表达式
template.h
#pragma once
#include <iostream>
#include <map>
#include <functional>
class RT
{
public:
int m_i = 5;
void myfunpt(int x, int y)
{
auto mylambda = [this, &x, y] //this表示可以引用本类的成员变量(既可以赋值又可以取值);&x表示引用传递(既可以赋值又可以取值);y表示值传递(只能取值,不能赋值)。
{
m_i = 6;
x = 3;
y;
};
mylambda();
}
};
class RT1
{
public:
int m_i = 5;
void myfunpt(int x, int y)
{
auto mylambda = [=, &x]//类成员变量m_i引用传递,myfunpt参数都是赋值传递,只有x为引用传递
{
m_i = 6;
x = 3;
y;
};
mylambda();
}
};
class RT2
{
public:
int m_i = 5;
void myfunpt(int x, int y)
{
auto mylambda = [&, y]//类成员变量m_i引用传递,myfunpt参数都是引用传递,只有x为值传递
{
m_i = 6;
x = 3;
y;
};
mylambda();
}
};
std::vector<std::function<bool(int)>> gv;
class ET
{
public:
int m_tmpValue = 7;
void addItem()
{
gv.push_back(
[abc = m_tmpValue](auto tv)//为了解决类删除后,m_tmpValue为随机值问题,拷贝到lambda里面的临时变量
{
std::cout << "tmpValue:" << abc << std::endl;
if (tv % abc == 0)
{
return true;
}
else
{
return false;
}
}
);
}
};
class ET1
{
public:
int m_tmpValue = 7;
void addItem()
{
gv.push_back(
[=](auto tv)
{
std::cout << "tmpValue:" << m_tmpValue << std::endl;
if (tv % m_tmpValue == 0)//当类删除后,这个m_tmpValue为随机值
{
return true;
}
else
{
return false;
}
}
);
}
};
main.cpp
#include <iostream>
#include "template.h"
using namespace std;
int main()
{
ET *pet = new ET();
pet->addItem();
delete pet;
gv[0](10);//m_tmpValue为随机值
ET1 *pet1 = new ET1();
pet1->addItem();
delete pet1;
gv[0](10);//m_tmpValue值不受对象删除影响
}
[=] 表示值传递(只能取值,不能赋值)。如果定义在类中,对成员变量是引用传递。
[&] 引用传递(既可以赋值又可以取值); 如果定义在类中,对成员变量是引用传递。
[=, &x] 表示值传递(只能取值,不能赋值)。只有x为引用传递。
[&, x] 引用传递(既可以赋值又可以取值); 只有x为值传递。