Lambda - C++11, 1 of n

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"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值