《C++Primer》中對lambda表達式的解釋如下:
lambda表達式表示一個可調用的代碼單元。我們可以將其理解爲一個未命名的內聯函數。
微軟官網對lambda表達式的解釋如下:
[] //未定義變量.試圖在Lambda內使用任何外部變量都是錯誤的.
[x, &y] //x 按值捕獲, y 按引用捕獲.
[&] //用到的任何外部變量都隱式按引用捕獲
[=] //用到的任何外部變量都隱式按值捕獲
[&, x] //x顯式地按值捕獲. 其它變量按引用捕獲
[=, &z] //z按引用捕獲. 其它變量按值捕獲
Lambda表達式的一個重要用途
std::sort(v.begin(), v.end(), [](int x, int y) {
return Weight(x) < Weight(y);
});
int weight = 3;
int sum = 0;
// Captures `weight` by value and `sum` by reference.
std::for_each(v.begin(), v.end(), [weight, &sum](int x) {
sum += weight * x;
});
std::set<int> blacklist = {7, 8, 9};
std::vector<int> digits = {3, 9, 1, 8, 4, 7, 1};
digits.erase(std::remove_if(digits.begin(), digits.end(), [&blacklist](int i) {
return blacklist.find(i) != blacklist.end();
}),
digits.end());
Lambda表達式的使用建議
- Keep unnamed lambdas short. If a lambda body is more than maybe five lines long, prefer to give the lambda a name, or to use a named function instead of a lambda.