您的位置:首页 > 其它

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

2012-04-20 04:50 513 查看
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下场取胜,提前夺冠!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: