• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >C语言 > 实例讲解C++编程中lambda表达式的使用

实例讲解C++编程中lambda表达式的使用

作者: 字体:[增加 减小] 来源:互联网 时间:2017-05-28

通过本文主要向大家介绍了c++11 lambda表达式,lambda表达式c++,c++11 lambda,c++ lambda,lambda表达式等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

函数对象与Lambdas
你编写代码时,尤其是使用 STL 算法时,可能会使用函数指针和函数对象来解决问题和执行计算。函数指针和函数对象各有利弊。例如,函数指针具有最低的语法开销,但不保持范围内的状态,函数对象可保持状态,但需要类定义的语法开销。
lambda 结合了函数指针和函数对象的优点并避免其缺点。lambda 与函数对象相似的是灵活并且可以保持状态,但不同的是其简洁的语法不需要显式类定义。 使用lambda,相比等效的函数对象代码,您可以写出不太复杂并且不容易出错的代码。
下面的示例比较lambda和函数对象的使用。 第一个示例使用 lambda 向控制台打印 vector 对象中的每个元素是偶数还是奇数。第二个示例使用函数对象来完成相同任务。
示例 1:使用 lambda
此示例将一个 lambda 传递给 for_each 函数。该 lambda 打印一个结果,该结果指出 vector 对象中的每个元素是偶数还是奇数。
代码

// 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 = 1; 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;
}

</div>

输出

1 is even

2 is odd

3 is even

4 is odd

5 is even

6 is odd

7 is even

8 is odd

9 is even

There are 4 even numbers in the vector.

</div>

批注
在此示例中,for_each 函数的第三个参数是一个lambda。 [&evenCount] 部分指定表达式的捕获子句,(int n) 指定参数列表,剩余部分指定表达式的主体。
示例 2:使用函数对象
有时 lambda 过于庞大,无法在上一示例的基础上大幅度扩展。下一示例使用函数对象(而非 lambda)以及 for_each 函数,以产生与示例 1 相同的结果。两个示例都在 vector 对象中存储偶数的个数。为保持运算的状态,FunctorClass 类通过引用存储 m_evenCount 变量作为成员变量。为执行该运算,FunctorClass 实现函数调用运算符 operator()。Visual C++ 编译器生成的代码与示例 1 中的 lambda 代码在大小和性能上相差无几。对于类似本文中示例的基本问题,较为简单的 lambda 设计可能优于函数对象设计。但是,如果你认为该功能在将来可能需要重大扩展,则使用函数对象设计,这样代码维护会更简单。
有关 operator() 的详细信息,请参阅函数调用 (C++)。

代码

// 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 = 1; 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;
}

</div>

输出

1 is even

2 is odd

3 is even

4 is odd

5 is even

6 is odd

7 is even

8 is odd

9 is even

There are 4 even numbers in the vector.

</div>


声明 Lambda 表达式
示例 1
由于 lambda 表达式已类型化,所以你可以将其指派给 auto 变量或 function 对象,如下所示:
代码

// declaring_lambda_expressions1.cpp
// compile with: /EHsc /W4
#include <functional>
#include <iostream>

int main()
{

 using namespace std;

 // Assign the lambda expression that adds two numbers to an auto variable.
 auto f1 = [](int x, int y) { return x + y; };

 cout << f1(2, 3) << endl;

 // Assign the same lambda expression to a function object.
 function<int(int, int)> f2 = [](int x, int y) { return x + y; };

 cout << f2(3, 4) << endl;
}

</div>

输出

5
7
</div>

备注
虽然 lambda 表达式多在函数的主体中声明,但是可以在初始化变量的任何地方声明。
示例 2
Visual C++ 编译器将在声明而非调用 lambda 表达式时,将表达式绑定到捕获的变量。以下示例显示一个通过值捕获局部变量 i 并通过引用捕获局部变量 j 的 lambda 表达式。由于 lambda 表达式通过值捕获 i,因此在程序后面部分中重新指派 i 不影响该表达式的结果。但是,由于 lambda 表达式通过引用捕获 j,因此重新指派 j 会影响该表达式的结果。
代码

// declaring_lambda_expressions2.cpp
// compile with: /EHsc /W4
#include <functional>
#include <iostream>

int main()
{
 using namespace std;

 int i = 3;
 int j = 5;

 // The following lambda expression captures i by value and
 // j by reference.
 function<int (void)> f = [i, &j] { return i + j; };

 // Change the values of i and j.
 i = 22;
 j = 44;

 // Call f and print its result.
 cout << f() << endl;
}

</div>

输出

47
</div>

调用 Lambda 表达式
你可以立即调用 lambda 表达式,如下面的代码片段所示。第二个代码片段演示如何将 lambda 作为参数传递给标准模板库 (STL) 算法,例如 find_if。
示例 1
以下示例声明的 lambda 表达式将返回两个整数的总和并使用参数 5 和 4 立即调用该表达式:
代码

// calling_lambda_expressions1.cpp
// compile with: /EHsc
#include <iostream>

int main()
{
 using namespace std;
 int n = [] (int x, int y) { return x + y; }(5, 4);
 cout << n << endl;
}

</div>

输出

示例 2
以下示例将 lambda 表达式作为参数传递给 find_if 函数。如果 lambda 表达式的参数是偶数,则返回 true。
代码

// calling_lambda_expressions2.cpp
// compile with: /EHsc /W4
#include <list>
#include <algorithm>
#include <iostream>

int main()
{
 using namespace std;

 // Create a list of integers with a few initial elements.
 list<int> numbers;
 numbers.push_back(13);
 numbers.push_back(17);
 numbers.push_back(42);
 numbers.push_back(46);
 numbers.push_back(99);

 // Use the find_if function and a lambda expr



 
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • C++ 中使用lambda代替 unique_ptr 的Deleter的方法
  • 基于C++ Lambda表达式的程序优化
  • C++ 中lambda表达式的编译器实现原理
  • C++ 中的Lambda表达式写法
  • C++11中lambda、std::function和std:bind详解
  • 浅析C++11新特性的Lambda表达式
  • 实例讲解C++编程中lambda表达式的使用
  • C++中的Lambda表达式详解
  • C++实现的一个可以写递归lambda的Y函数

相关文章

  • 2017-05-28C语言中读取时间日期的基本方法
  • 2017-05-28浅析C/C++中的可变参数与默认参数
  • 2017-05-28for循环中删除map中的元素valgrind检测提示error:Invalid read of size 8
  • 2017-05-28C++中求旋转数组中的最小数字(经典面试题)
  • 2017-05-28DSP中浮点转定点运算--浮点数的存储格式
  • 2017-05-28C/C++函数调用的几种方式总结
  • 2017-05-28冒泡算法的改进具体实现
  • 2017-05-28C/C++程序开发中实现信息隐藏的三种类型
  • 2017-05-28wince禁止程序标题栏上的退出按钮示例
  • 2017-05-28详解C语言位域的使用与注意事项

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • 主流操作系统平台的宏定义
    • Linux环境g++编译GDAL动态库操作方法
    • Linux环境下段错误的产生原因及调试方法小结
    • C++设置超时时间的简单实现方法
    • C++实现顺序表的方法
    • 约瑟夫环问题(数组法)c语言实现
    • 深入C/C++浮点数在内存中的存储方式详解
    • 用c语言实现2000内既能被3整除又能被7整除的个数
    • C++无法重载点符号、::、sizeof等的原因
    • 纯C语言:分治假币问题源码分享

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有