2014年01月24日 星期五 11:18
lambda是C++11标准引入的新特性之一,lambda并不是一种新概念,在很多现代编程语言中都有匿名函数的概念,其主要用于编写临时性的方法,相对于正式的函数和Function Object来说,其编写更简单,更轻量级。
相对于传统的function,lambda功能也很齐全,可以访问外部变量,可以传入参数,也可以返回数据。
编程示例如下:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main(int argc, char **argv)
{
auto lmd= [] {
cout << "Oh, lambda!" << endl;
};
lmd();
auto hello=[](string name) {
cout << "Hello, " << name << "." << endl;
};
hello("mengguang");
auto i=100;
auto incr=[&i] {
i++;
};
incr();
cout << i << endl;
auto concat=[](string first,string second) {
return first + " " + second;
};
string c=concat("Hello","World");
cout << c << endl;
vector<string> friends={"laomeng","laozhang","laoyang"};
for_each(friends.begin(),friends.end(),hello);
for_each(friends.begin(),friends.end(),
[] (string name) { cout << "Hi, " << name << endl;});
vector<int> numbers;
for(int i=1;i<=100;i++){
numbers.push_back(i);
}
auto result=0;
for_each(numbers.begin(),numbers.end(),
[&result](int n){ result += n;});
cout << result << endl;
return 0;
}
参考资料:
http://stackoverflow.com/a/7627218
2014年01月26日 星期日 10:24
这个写法。感觉好别扭,
2014年01月26日 星期日 16:43
这个标点的用法,貌似也挺别扭。一定是我打开帖子的方式不对。
Zeuux © 2025
京ICP备05028076号