Lambdas(C++11新增)
2016-03-02 17:50
387 查看
Lambdas 语法
no parameters: […] {…}[] { std::cout << "hello lambda" << std::endl; }
You can call it directly:
[] { std::cout << "hello lambda" << std::endl; } (); // prints ‘‘hello lambda’’
or pass it to objects to get called:
auto l = [] { std::cout << "hello lambda" << std::endl; }; ... l(); // prints ‘‘hello lambda’’
has parameters: […] (…) {…}
A lambda can have parameters specified in parentheses, just like any other function:
auto l = [] (const std::string& s) { std::cout << s << std::endl; }; l("hello lambda"); // prints ‘‘hello lambda’’
It cannot be templates.
return something. Without any specific definition of the return type, it is
deduced from the return value. For example, the return type of the following lambda is int:
[] { return 42; }
Others, the following lambda returns 42.0:
[] () -> double { return 42; }
Captures (Access to Outer Scope)
[=] means that the outer scope is passed to the lambda by value. Thus, you can read but notmodify all data that was readable where the lambda was defined.
[&] means that the outer scope is passed to the lambda by reference. Thus, you have write access
to all data that was valid when the lambda was defined, provided that you had write access there.For example:
int x=0; int y=42; auto qqq = [x, &y] { std::cout << "x: " << x << std::endl; std::cout << "y: " << y << std::endl; ++y; // OK // ++i; // ERROR!!!!! }; x = y = 77; qqq(); qqq(); std::cout << "finaly: " << y << std::endl;
OUTPUT:
x: 0 y: 77 x: 0 y: 78 finaly: 79
Instead of [x, &y], you could also have specified [=, &y] to pass y by reference and all other
objects by value.
multable
To have a mixture of passing by value and passing by reference, you can declare the lambda as mutable. In that case, objects are passed by value, but inside the function object defined by the lambda, you have write access to the passed value. For example:
int id = 0; auto f = [id] () mutable { std::cout << "id: " << id << std::endl; ++id; // OK }; id = 42; f(); f(); f(); std::cout << id << std::endl;
has the following output:
id: 0 id: 1 id: 2 42
Type of Lambdas
Using Lambdas
本文来源:《C++ Standard Library》(2nd Edition) Typed By:IFuMI相关文章推荐
- C语言 简单的队列(数组队列)
- c语言:Hanoi(汉诺)塔问题,求移动盘子的步骤
- Boost 学习之Align-序言部分
- 【C++】实现动态顺序表的PushBack(),PopBack(),PushFront(),PopFront(),Find(),Insert
- C++学生信息处理
- 【C++函数重载】求3个数中最大的数…
- 【c++】用c++编写的求任意区间的素…
- 构造函数
- #include<bits/stdc++.h>
- C++中ShallowCopy和DeepCopy的区别
- VC++中窄字节、宽字节、多字节
- 项目开发中值得推荐的C/C++框架和库总结
- 第1章 软件工程基本原理和C++类
- C++调用lib或dll文件
- 【C语言】输入一组整数,求出这组数字子序列和中最大值
- 黑马程序员-C语言回顾-指针
- 类(Classes)的定义与实现
- Effective C++ 笔记:4设计与声明
- C语言学习
- C++中字符串字面值和字符相加