Skip to content

C++11 learning #22

Description

@pfjhyyj

lambda function

基本形式
[capture list] (parameter list) mutable exception -> return type {function body}
capture list (捕获列表): 在lambda所在函数中定义的局部变量的列表 (可为空

[ ] 空捕获列表
[name1] name 为局部变量名,使用值捕获
[&name] name 为局部变量名,使用引用捕获
[&] 隐式捕获(引用) [=] 隐式捕获(值)
(lambda中需要什么就获取什么)

parameter list(参数列表): 调用时需要使用的参数的列表(可为空)
mutable : 使用此声明则lambda函数中可以更改捕获列表中变量的值(可不使用)
exception : 表示函数可以抛出的异常类
return type : 说明返回类型,部分情况下可以省略(可为空)

可以按照return的类型来判断
如果无返回值,则被认为是返回void类型
以下情况会产生编译错误

[ ] (int i) {if (i < 0) return -i; else return i;}

编译器推断返回类型为void,但返回了int

[ ] (int i) {return i < 0 ? -i : i;}

编译可以通过,返回int

funtion body : 函数体

用处

当需要一个不需要在很多地方多次使用的函数时,lambda表达式简单而有效
如在find_if中

auto wc = find_if(w.begin(), w.end(), [_size] (const string &a) return {a.size() >= _size;})

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions