Lambda
1.概述
C++11 introduced lambdas,allowing the definition of inline functionality,which can be used as a parameter or a local object. Lambdas change the way the C++ standard library is used.
A lambda is a definition of functionality that can be defined inside statements and expressions.Thus,you can use a lambdaas an inline function. The minimal lambda function has no parameters and simply does something.
[] {
std::cout << "helllo lambda" << std::endl;
}();
auto I = [] {
std::cout << "helllo lambda" << std::endl;
}();
I();
2.Lambda
3.代码示例
int id = 0 ;
auto f = [id]()mutable {
cout << "id: " << id << endl;
++id;
};
id = 42;
f();
f();
f();
std::cout << id << std::endl;
int id = 0 ;
auto f = [&id]()mutable {
cout << "id: " << id << endl;
++id;
};
id = 42;
f();
f();
f();
std::cout << id << std::endl;
int id = 0 ;
auto f = [id]() {
cout << "id: " << id << endl;
++id;
};
id = 42;
f();
f();
f();
std::cout << id << std::endl;
int id = 0;
auto f2 = [id]() mutable ->int {
cout << "id:" << id << endl;
++id;
static int x = 5;
int y = 6;
return id;
};
id = 42;
f2();
可以声明变量,可以返回数值4.编译器生成
Here is what complier generates for lambda's
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class UnNamedLocalFunction {
private:
int localVar;
public:
UnNamedLocalFunction(int var) : localVar(var) {}
bool operator() (int val) {
return val == localVar;
}
};
int main() {
int tobefound = 5;
auto lambda1 = [tobefound] (int val) { return val == tobefound; };
UnNamedLocalFunction lambda2(tobefound);
bool b1 = lambda1(5);
bool b2 = lambda2(5);
std::cout << "b1: " << b1 << endl;
std::cout << "b2: " << b2 << endl;
return 0;
}
5.Lambda is an anonymous function object
The type of a lambda is an anonymous function object(or functor) that is unique for each lambda expression.Thus, todeclare objects of that type, you need templates or auto.If you need the type, you can usedecltype(), which is, for example, required to pass a lambdaas hash function or ordering or sorting criterion to associative or unordered containers.
6.定制STL表现