C++11里面的Lambda表达式
Lambda Expressions in C++
About Lambdas
Function Objects vs. Lambdas
When you write code, you probably use function pointers and function objects to solve problems and perform calculations, especially when you use STL algorithms. Function pointers and function objects have advantages and disadvantages—for example, function pointers have minimal syntactic overhead but do not retain state within a scope, and function objects can maintain state but require the syntactic overhead of a class definition.
A lambda combines the benefits of function pointers and function objects and avoids their disadvantages. Like a function objects, a lambda is flexible and can maintain state, but unlike a function object, its compact syntax doesn't require a class definition. By using lambdas, you can write code that's less cumbersome and less prone to errors than the code for an equivalent function object.
The following examples compare the use of a lambda to the use of a function object. The first example uses a lambda to print to the console whether each element in a vector object is even or odd. The second example uses a function object to accomplish the same task.
当你写代码时,你可能会用到函数指针,或函数对象来解决问题或者进行演算,尤其当你用STL algorithms时。函数指针和函数对象(或许可理解为仿函数?)有优缺点——例如,函数指针有最小的句法开销(?)但不能在作用域中保持状态(?),而函数对象能够保持状态却需要一个类的定义(相较而言较大的句法开销)
Example 1: Using a Lambda
// even_lambda.cpp
// compile with: cl /EHsc /nologo /W4 /MTd
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std; int main()
{
// Create a vector object that contains 10 elements.
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
} // Count the number of even numbers in the vector by
// using the for_each function and a lambda.
int evenCount = 0;
for_each(v.begin(), v.end(), [&evenCount] (int n) {
cout << n; if (n % 2 == 0) {
cout << " is even " << endl;
++evenCount;
} else {
cout << " is odd " << endl;
}
}); // Print the count of even numbers to the console.
cout << "There are " << evenCount
<< " even numbers in the vector." << endl;
}
Output
0 is even
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
There are 5 even numbers in the vector.
Comments
Example 2: Using a Function Object
Sometimes a lambda would be too unwieldy to extend much further than the previous example. The next example uses a function object instead of a lambda, together with the for_each function, to produce the same results as Example 1. Both examples store the count of even numbers in a vector object. To maintain the state of the operation, the FunctorClass class stores the m_evenCount variable by reference as a member variable. To perform the operation, FunctorClass implements the function-call operator, operator(). The Visual C++ compiler generates code that is comparable in size and performance to the lambda code in Example 1. For a basic problem like the one in this article, the simpler lambda design is probably better than the function-object design. However, if you think that the functionality might require significant expansion in the future, then use a function object design so that code maintenance will be easier.
For more information about the operator(), see Function Call (C++). For more information about the for_eachfunction, see for_each.
有时候lambda表达式过于繁杂(扩充功能)。下一个例子采用了函数对象,同样使用for_each。都是数vector元素中偶数个数,为保持操作状态,FunctorClass类保存了m_evenCount变量作为一个成员变量的引用。为实现功能,FunctorClass重载(implement?)了function-call操作符,operator()。VC++编译器产生了与之相当大小和表现得lambda表达式代码(例一)。在这个基本问题中,简易的lambda表达式设计可能比函数对象更好。然而,若你认为functionality(函数性?)可能需要一个明确的扩展,那么就用函数对象写代码,那会简单些。
// even_functor.cpp
// compile with: /EHsc
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std; class FunctorClass
{
public:
// The required constructor for this example.
explicit FunctorClass(int& evenCount)
: m_evenCount(evenCount)
{
} // The function-call operator prints whether the number is
// even or odd. If the number is even, this method updates
// the counter.
void operator()(int n) const
{
cout << n; if (n % 2 == 0) {
cout << " is even " << endl;
++m_evenCount;
} else {
cout << " is odd " << endl;
}
} private:
// Default assignment operator to silence warning C4512.
FunctorClass& operator=(const FunctorClass&); int& m_evenCount; // the number of even variables in the vector.
}; int main()
{
// Create a vector object that contains 10 elements.
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
} // Count the number of even numbers in the vector by
// using the for_each function and a function object.
int evenCount = 0;
for_each(v.begin(), v.end(), FunctorClass(evenCount)); // Print the count of even numbers to the console.
cout << "There are " << evenCount
<< " even numbers in the vector." << endl;
}
Summary
C++11里面的Lambda表达式的更多相关文章
- C++11中的Lambda表达式
原文地址:C++中的Lambda表达式 作者:果冻想 一直都在提醒自己,我是搞C++的:但是当C++11出来这么长时间了,我却没有跟着队伍走,发现很对不起自己的身份,也还好,发现自己也有段时间没有写C ...
- 【转】C++11新特性——lambda表达式
C++11的一大亮点就是引入了Lambda表达式.利用Lambda表达式,可以方便的定义和创建匿名函数.对于C++这门语言来说来说,“Lambda表达式”或“匿名函数”这些概念听起来好像很深奥,但很多 ...
- C++11新特性 lambda表达式
C++11 添加了了一个名为lambda表达式的功能,可以用于添加匿名函数 语法: [capture_block](parameter) mutable exception_specification ...
- C++ 11 中的 Lambda 表达式的使用
Lambda在C#中使用得非常频繁,并且可以使代码变得简洁,优雅. 在C++11 中也加入了 Lambda. 它是这个样子的 [] () {}... 是的三种括号开会的节奏~ [] 的作用是表示La ...
- 「C++11」Lambda 表达式
维基百科上面对于 lambda 的引入是如下描述的: 在标准 C++,特别是当使用 C++ 标准程序库算法函数诸如 sort 和 find.用户经常希望能够在算法函数调用的附近定义一个临时的述部函数( ...
- c++11 新特性之lambda表达式
写过c#之后,觉得c#里的lambda表达式和delegate配合使用,这样的机制用起来非常爽.c++11也有了lambda表达式,形式上有细小的差异.形式如下: c#:(input paramete ...
- C++11 lambda表达式学习
lambda表达式是函数式编程的基础.咱对于函数式编程也没有足够的理解,因此这里不敢胡言乱语,有兴趣的可以自己查找相关资料看下.这里只是介绍C++11中的lambda表达式自己的认识.这里有参考文档h ...
- C++ 11 Lambda表达式
C++11的一大亮点就是引入了Lambda表达式.利用Lambda表达式,可以方便的定义和创建匿名函数.对于C++这门语言来说来说,“Lambda表达式”或“匿名函数”这些概念听起来好像很深奥,但很多 ...
- C++ 11 Lambda表达式、auto、function、bind、final、override
接触了cocos2dx 3.0,就必须得看C++ 11了.有分享过帖子:[转帖]漫话C++0x(四) —- function, bind和lambda.其实最后的Lambda没太怎么看懂. 看不懂没关 ...
随机推荐
- Arcgis API for Android之GPS定位
欢迎大家增加Arcgis API for Android的QQ交流群:337469080 先说说写这篇文章的原因吧,在群内讨论的过程中,有人提到了定位的问题,刚好,自己曾经在做相关工作的时候做过相关的 ...
- IT English Collection(9) of Objective-C
1 前言 今天我们来解除一篇有关Objective-C的介绍文章,详情如下. 2 详述 2.1 原文 Objective-C defines a small but powerful set of e ...
- Oracle SQL ANY和ALL语句
Oracle的嵌套子查询可以使用Some,Any和All对子查询中返回的多行结果进行处理. Some表示满足其中一个的含义,是用or串起来的比较从句. 例如:SELECT * FROM emp WHE ...
- js 闭包和回调
原文:http://www.cnblogs.com/yuyuj/p/4525530.html 之前的工作都是基于老大搭建的框架,仿照他写的例子写的请求,很多东东也都做好了封装,只需要了解下直接调用就好 ...
- 正则去掉html标签
return System.Text.RegularExpressions.Regex.Replace(HTMLStr, "<[^>]*>", "&qu ...
- Oracle游标cursor2显示的游标等
--在一中我们介绍了实现过程 select *from stud; declare cursor mycur is select id,name from stud;--1声明 v_id intege ...
- 诡异的SpriteKit 游戏查错
在Endless Runner 游戏中,做了一些atlas后,发现有个问题,当player跳跃起来的时候,发现他没有动画了,被默认的X图片代替.原来的图像是这样的. 在增加了一些动画后,我的效果就成这 ...
- TOJ3596 二维背包
3596. Watch The Movie Time Limit: 2.0 Seconds Memory Limit: 65536KTotal Runs: 424 Accepted Run ...
- mysql索引之普通索引
1,普通索引的创建 普通索引可以在建表的时候创建 sql : create table temp2(id int(10) not null auto_increment ,title varchar( ...
- mysql查询unicode字符串
mysql查询的时候会将\干掉,可以用mysql的like通配符来做like '%\u5f20\u4e09%'变成like '%_u5f20_u4e09%'