Lambda - C++11, 1 of n
来源:互联网 发布:一朝成名天下知 编辑:程序博客网 时间:2024/06/06 03:42
Definitely my favorite!
The definition:
[capture clause] (parameters) mutable ->returntype{ lambda body...}
[] : Capture nothing
[x] : Capture by value
[&x] : Capture by reference
[&] : Capture all (all variables in lambda body scope) by reference
[=] : Capture all (all variables in lambda body scope) by value
[&, x]: Capture all (all variables in lambda body scope) but x by reference
[=, &x] : Capture all (all variables in lambda body scope) but x by value
[x, &y] : Capture x by value, y by reference
If 'mutable' is specified, it is allowed to mutate the values that have been captured by value.
1) Capture nothing, return void.
vector<int> v = {1, 2, 3};
for_each(v.begin(), v.end(), [] (int val) {
cout << val << " ";
});
2) Capture by value, return void.
int y = 4;
vector<int> v = {1, 2, 3};
for_each(v.begin(), v.end(), [y] (int val) {
cout << val * y<< " ";
});
cout << "\n" << y << "\n";
3) Capture by reference, return void.
int y = 1;
vector<int> v = {1, 2, 3};
for_each(v.begin(), v.end(), [&y] (int val) {
y *= val;
});
cout << y << "\n";
4) Capture all by reference, return void.
int y = 1;
int z = 1;
vector<int> v = {1, 2, 3};
for_each(v.begin(), v.end(), [&] (int val) {
y *= val;
z *= y;
});
cout << y << "\n" << z << "\n";
5) Capture all by value, return void (invalid case).
int y = 1;
int z = 1;
vector<int> v = {1, 2, 3};
for_each(v.begin(), v.end(), [=] (int val) {
y *= val;
z *= y;
cout << y << " " << z << " ";
});
/home/lpadmin/c++/src/lambda.cpp:12:39: error: assignment of read-only variable ‘y’
/home/lpadmin/c++/src/lambda.cpp:13:39: error: assignment of read-only variable ‘z’
valid case:
int y = 1;
int z = 1;
vector<int> v = {1, 2, 3};
for_each(v.begin(), v.end(), [=] (int val) mutable {
y *= val;
z *= y;
cout << y << " " << z << " ";
});
cout << "\n" << y << "\n" << z << "\n";
6) Capture nothing, return int (like transform).
vector<int> v = {1, 2, 3};
auto f = [](int val)->int {
return val * 2;
};
for(auto &i: v)
{
i = f(i);
}
7) By default, Lambdas have "no default constructor and assignment operator are defined"
- Lambda - C++11, 1 of n
- [c#]: Lambda
- C#-Lambda
- c#Lambda
- c#lambda
- ZOJ 3175 Number of Containers(n/1+n/2+...+n/(n-1)+n/n求法)
- Syntax of Lambda Expressions
- State of the Lambda
- Translation of Lambda Expressions
- Python idioms, 1 of n
- Python performance 1 of n
- C++11 学习笔记 lambda表达式
- 【C++】C++11特性:lambda和function
- C++11 学习笔记 lambda表达式
- C++11 学习笔记 lambda表达式
- Windows Store apps开发[26]C++/CX Part 1 of [n]: 一个简单的类
- 【c/c++】Lambda表达式
- Concurrency 1, async and future - C++11, 8 of n
- XmlToJson
- hdu2680
- Android自动打包、签名、优化、上传ANT脚本
- Sql Server A表汇总到B表存储过程(直接赋参数用,源码)
- poj 1318 Word Amalgamation
- Lambda - C++11, 1 of n
- Android使用Ant自动编译签名打包详解
- 学习-PHP-继承类-全局变量
- OpenGL Frame Buffer Object
- objective-C中@class和#import的区别
- 连接VPN问题
- linux常用命令杂谈
- 16周任务二 salary 文件的操作
- hdu 1506 Largest Rectangle in a Histogram DP 单调队列