concurrency runtime学习笔记之一:Lambda表达式

lambda表达式不是什么新玩意,熟悉.net的朋友一定不会陌生,但对于C++却是新标准C++0x推出后才有的,其功能之强大,堪称编程利器。一般认为lambda表达式是一个匿名函数,其返回类型是function对象,例如可以这样来声明:

#include <functional>

int main()
{
   // Assign the lambda expression
   auto f1 = [] (int x, int y) { return x + y; }; 

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

当然这样的声明很少会用到,lambda表达式一般都是和泛型算法结合起来用,用来取代函数对象或者函数指针。再看一个例子,这个例子用来判断是否为偶数:

#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 expression.
   int evenCount = 0;
   for_each(v.begin(), v.end(), [&evenCount] (int n)
{ cout
<< n; if (n % 2 == 0) { cout << " is even " << endl; // Increment the counter. 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; }

lambda表达式也可以用作函数参数。因为表达式不可能被赋值,也就是说表达式一直处于赋值运算符的右边,所以可以通过右值引用&&传入函数。还是给出一个计算时间的常用例子,由于使用了泛型,这里可以传入任何表达式,否则需要给出具体function对象作为表达式类型。

// Calls the provided work function and returns the number of milliseconds 
// that it takes to call that function.
template <class Function>
__int64 time_call(Function&& f)
{
   __int64 begin = GetTickCount();
   f(); //这里的括号表示运行表达式
   return GetTickCount() - begin;
}

lambda表达式在多线程编程方面也有广泛的引用,比如并行和异步,这个以后会谈到。

最后给一个比较有意思的表达式,这是一个没有引用,没有参数,没有内容的lambda表达式,完全可以在VS下编译通过。

  [](){}();

 

 

 ------------------------------------------------------------------

此文是本人博客第一篇原创,其中的例子引用了microsoft的官方文档。

本人现居德国多特蒙德,谨以此文献给多特蒙德BVB,预祝BVB下场取胜,提前夺冠!

转载于:https://www.cnblogs.com/xfu123/archive/2012/04/20/2458659.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值