2011年1月5日星期三

lambda表达式

对于std::for_each()这样的算法,是最适合使用lambda表达式这样的小技巧的

lambda表示并不是一个必须的东西,跟它有相同作用的还有function object和函数指针.函数指针的缺点在于没办法保存中间状态,但是效率相对较高.而function object作为一个自定义类型当然能保持中间状态,但是写起来也太繁琐了.

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;
}

总的来说,基本规则就是
1. [=], [&] 表示在lambda函数里可以访问当前所有变量,其中=隐含了this
2. [=, &a, &b] 表示除ab按引用传递,其他均按值传递
3. [a, &b] a按值传递,b按引用传递

这儿有个参考: http://msdn.microsoft.com/en-us/library/dd293599.aspx
g++ 4.5版本之后才支持这个东西, vc我没有查过,貌似也是vc2010才支持

--
caosuwei <caosuwei@gmail.com>

没有评论: