lambda表达式

2019-07-31  本文已影响0人  ustclcl

lambda表达式

介绍

一个lambda表达式表示一个可调用的代码单元,可以将其理解为一个未命名的内联函数。形式为

[capture list](parameter list) -> return type { function body}
//必须使用尾置返回

几个特点

lambda表达式的捕获

void fun1()
{
    size_t v1 = 21;
    auto f = [v1]{return v1;}; //省略了参数列表
    v1 = 0;
    cout << f();
}

输出21

void fun2()
{
    size_t v2 = 21;
    auto f2 = [&v2] {return v2;};
    v2 = 0;
    cout << f2();
}

将输出0

void fun3()
{
    size_t v3 = 21;
    auto f3 = [&] {return v3;};
    v3 = 0;
    cout << f3();
}

输出0

mutable

对于值捕获,lambda表达式不能改变捕获的参数,如

void fun4()
{
    size_t v4 =21;
    auto f4 = [=] (int i)  {return (++v4) + i;};
    cout << endl << f4(9);
}

编译错误

error: increment of read-only variable 'v4'|

可以在参数列表后面加mutable,同时即使没有参数,参数列表也不能省略了。

void fun4()
{
    size_t v4 =21;
    auto f4 = [=] (int i) mutable {return (++v4) + i;};
    cout << endl << f4(9);
}

而用引用捕获时就不需要了

void fun4()
{
    size_t v4 =21;
    auto f4 = [&] (int i)  {return (++v4) + i;};
    cout << endl << f4(9);
}

返回

当函数体不是只有一条return语句时需要指定返回类型,且必须用尾置返回类型。

上一篇 下一篇

猜你喜欢

热点阅读