【C++11】lambda表达式 匿名函数详解

在刷牛客时,看到这段lambda表达式可以提高输入输出速度

1 static const auto io_sync_off = []()
2 {
3     // turn off sync
4     std::ios::sync_with_stdio(false);
5     // untie in/out streams
6     std::cin.tie(nullptr);
7     return nullptr;
8 }();

于是去详细了解C++11引入的 Lambda 表达式,和大家分享。

1、Lambda

先看这个例子,讲

// 作为 inline function, 可以作为参数或者无名对象

[]{ std::cout << "Hello Lambda" << std::endl; }


-----------------------------------------------------
// 单独写出来,调用
auto I = []{
   std::cout << "Hello Lambda" << std::endl;
};
 
 ...
 
 I();  // 打印  "Hello Lambda"

 

定义形式:

[captrue list] (parameter list) -> return type or exception { function body}

// 写的清楚点就是

[captrue list] (parameter list) -> return type {
     function body
}

capture list捕获列表

parameter list 参数列表

-> return type or exception 尾置返回类型或异常

function body 函数体

2、举例

auto func1 = [](const string &a, const string &b){
    return a.size() > b.size();        
}

//等价于

class NoNameClass{
public:
    bool operator()(const string &a, const string &b){
        return a.size() > b.size();
    }
};

3、注意点

(1)参数列表不能有默认值

(2)可以省略参数列表和返回类型(默认void),但必须有捕获列表和函数体; []{return 1;} 

(3)如果包含return以外的任何语句,默认返回void; 特殊的,若要有返回类型,则必须尾置返回指定类型 ->return type

1 // 包含多个语句,且需要返回int,就必须尾置类型
2  auto f = [](int i) ->int {
3     if(i<0) return -i;
4     else return i;
5  }

(4)

猜你喜欢

转载自www.cnblogs.com/jcxioo/p/12799397.html