lambda本质是inline函数,将inline函数的定义作为一个对象,可以把函数保存成一个local变量,也可以作为一个参数,由[]开头
[]用于捕获上下文变量供lambda表达式使用
// lambda c++
auto local = []
() {
std::cout << "a " << a << "b " << b << "c " << c << std::endl;
};
local();
作为一个模板参数传入
template<typename Func>
void printUseFunc(Func func, int a, int b, int c) {
func(a,b,c);
}
int main(){
printUseFunc([](int a,int b,int c){
std::cout<<"a"<<a<<"b"<<b<<"c"<<c<<std::endl;
},
1,2,3);
}
lambda函数主要用于解决以下问题:
- 有的时候调用和实现在不同文件
- 有的时候实现十分简单
主要配合算法一起使用,[]可以引入一些local变量,以值的方式传入a,b,c
int a = 1;
int b = 2;
int c = 3;
// lambda c++
auto local = [a,b,c]
() {
std::cout << "a " << a << "b " << b << "c " << c << std::endl;
};
local();
用=表示外部所有变量值的拷贝,用&传入表示外部所有变量的引用
int a = 1;
int b = 2;
int c = 3;
// lambda c++
auto local = [&]
() {
std::cout << "a " << a << "b " << b << "c " << c << std::endl;
};
local();
lambda完整例子:
#include <functional>
#include <iostream>
void printInfo(int a, int b, int c) {
std::cout << "a " << a << "b " << b << "c " << c <<std::endl;
}
struct Print {
void operator()(int a, int b, int c) const {
std::cout << "a " << a << "b " << b << "c " << c << std::endl;
}
};
template<typename T1, typename T2, typename T3>
void templatePrint(T1 a, T2 b, T3 c) {
std::cout << "a " << a << "b " << b << "c " << c << std::endl;
}
struct TemplatePrint {
template<typename T1, typename T2, typename T3>
void operator()(T1 a, T2 b, T3 c) const {
std::cout << "a " << a << "b " << b << "c " << c << std::endl;
}
};
inline void print
(int a, int b, int c) {
std::cout << "a " << a << "b " << b << "c " << c << std::endl;
}
template<typename Func>
void printUseFunc(Func func, int a, int b, int c) {
func(a,b,c);
}
int main() {
Print printUseClass;
TemplatePrint printUseTempClass;
print(1,2,3);
printInfo(1,2,3);
printUseClass(1,2,3);
templatePrint(1,2,3);
printUseTempClass(1,2,3);
int a = 1;
int b = 2;
int c = 3;
// lambda c++
auto local = [&]
() {
std::cout << "a " << a << "b " << b << "c " << c << std::endl;
};
local();
}