在编程的过程中,一般通过函数指针或者函数对象(仿函数)来计算或者解决问题,如排序sort和移除操作remove_if的参数中都有相应的谓词函数。函数指针虽然语法开销小,但是不能在作用域内保持状态(can not retain state within a scope)。函数对象(仿函数)能够retain the state within a scope,但是有大的语法开销。
lambda表达式能够综合二者的优点。能够减少代码量,同时不打乱程序的流程。
lambda规范式如下:
capture 指定了在可见域范围内 lambda 表达式的代码内可见得外部变量的列表,具体解释如下:
[a,&b]
a变量以值的方式被捕获,b以引用的方式被捕获。[this]
以值的方式捕获 this 指针。[&]
以引用的方式捕获所有的外部自动变量。[=]
以值的方式捕获所有的外部自动变量[]
不捕获外部的任何变量。
Params为指定的参数,mutable申明以值捕获的变量的值能够被修改。
exception 说明 lambda 表达式是否抛出异常(noexcept
),以及抛出何种异常,类似于void f() throw(X, Y)。
attribute 用来声明属性。
如使用lambda表达式对vector<int>对象求和:
//use lambda expression for get the sum of vec
int
sum = 0;
for_each(vec.begin(), vec.end(), [&sum](
int
x)
/*mutable*/
{
return
sum += x;} );
cout<<
"The sum of vec is:"
<<sum<<endl;
定义一个auto变量来存放lambda表达式对象:
auto
f1 = [](
int
x,
int
y) {
return
x + y; };
cout<<f1(3, 4)<<endl;
排序,
sort(vec.begin(), vec.end(), [](int x, int y) { return x < y; });
定义的同时实例化该lambda对象:
int n = [] (int x, int y) { return x + y; }(5, 4);
如何嵌套(nested) lambda expression:
int m = [](int x) { return [](int y) { return y * 2; }(x) + 3; }(5);
高阶lambda表达式:
//test high order lambda expression
auto
g = [] (
int
x) -> function<
int
(
int
)>
{
return
[x](
int
y) {
return
x + y ;};
};
auto
h = [] (
const
function<
int
(
int
)>& f,
int
z) {
return
f(z) + z;};
auto
result = h(g(45), 5);
cout<<
"The result of high order lb is :"
<<result<<endl;
在类中调用lambda表达式并显示或隐式访问this指针:
class Scale { public: // The constructor. explicit Scale(int scale) : _scale(scale) { } // Prints the product of each element in a vector object // and the scale value to the console. void ApplyScale(const vector<int>& v) const { for_each(v.begin(), v.end(), [this](int n) { cout << n * this->_scale << endl; });
//for_each(v.begin(), v.end(),
//[this](int n) { cout<<n*_scale<<endl;});
}
private:
int _scale;
};
给数组依次赋值:
int s[100];
int i = 0;
for_each(s, s + 100, [&i](int& x) { x = i++; });