Guide
syntax
syntax
[ capture clause ] (parameters) -> return-type
{
definition of method
}
capture
We can capture external variables from enclosing scope by three ways :
Capture by reference
Capture by value (making a copy)
Capture by both (mixed capture)
Syntax used for capturing variables :
[]: capture nothing
[&] : capture all external variable by reference
[=] : capture all external variable by value (making a copy)
[a, &b] : capture a by value and b by reference
[this] : Capture the this pointer of the enclosing class
C++11中的Lambda表达式捕获外部变量主要有以下形式:
捕获形式 说明
[] 不捕获任何外部变量
[变量名, …] 默认以值得形式捕获指定的多个外部变量(用逗号分隔),如果引用捕获,需要显示声明(使用&说明符)
[this] 以值的形式捕获this指针
[=] 以值的形式捕获所有外部变量
[&] 以引用形式捕获所有外部变量
[=, &x] 变量x以引用形式捕获,其余变量以传值形式捕获
[&, x] 变量x以值的形式捕获,其余变量以引用形式捕获
example code
#include <bits/stdc++.h>
using namespace std;
void test_labmda_0()
{
// call lambda with ending ();
[] ()
{
cout << "Hello, my Greek friends";
}();
// return value
auto l1 = [] ()
{
return 1;
} ; // compiler knows this returns an integer
auto l2 = [] () -> int
{
return 1;
} ; // now we're telling the compiler what we want
}
// Function to print vector
void printVector(const vector<int>& v)
{
// lambda expression to print vector
for_each(v.begin(), v.end(), [](int i)
{
std::cout << i << " ";
});
cout << endl;
}
void test_lambda_1()
{
vector<int> v {4, 1, 3, 5, 2, 3, 1, 7};
printVector(v);
// capture nothing
std::sort(v.begin(), v.end(), [](const int& a, const int& b) -> bool
{
return a > b;
});
printVector(v);
int ans = accumulate(v.begin(),v.end(),0,
[](int i,int j)
{
return i+j;
}
);
cout << "SUM = " << ans << endl;
}
void test_lambda_2()
{
vector<int> v1 = {3, 1, 7, 9};
vector<int> v2 = {10, 2, 7, 16, 9};
// access v1 and v2 by reference
auto pushinto = [&] (int m)
{
v1.push_back(m);
v2.push_back(m);
};
// it pushes 20 in both v1 and v2
pushinto(20);
// access v1 by value (copy)
auto printv = [v1]()
{
for (auto p = v1.begin(); p != v1.end(); p++)
{
cout << *p << " ";
}
cout << endl;
};
printv();
int N = 5;
// below snippet find first number greater than N
// [N] denotes, can access only N by value
vector<int>:: iterator p = find_if(v1.begin(), v1.end(), [N](int i)
{
return i > N;
});
cout << "First number greater than 5 is : " << *p << endl;
}
class Foo
{
public:
Foo () : _x( 3 ) {}
void func ()
{
// a very silly, but illustrative way of printing out the value of _x
[this] ()
{
cout << this->_x;
} ();
}
private:
int _x;
};
int test_labmda_3()
{
Foo f;
f.func();
}
void main_demo()
{
test_lambda_0();
test_lambda_1();
test_lambda_2();
test_labmda_3();
}
int main(int argc, char const *argv[])
{
main_demo();
return 0;
}
Reference
- c++11-lambda-closures
- c-lambda-function-tutorial-lambda-expression-in-c-example
- lambda-expression-in-c
History
- 20180823: created.