Lambda始自C++ 11,是一種在表達式或語句內指定函數行為的定義式。
你可以定義函數行為作為對象,以inline實參的形式傳給算法作為predicate(判斷式)。
eg:
std:transform(coll.begin(), coll.end(), // source
coll.begin(), // destination
#include <algorithm> #include <deque> #include <iostream> #include "LambdaTest.h" #include "../../Core/ContainerUtil.h" using namespace std; deque<int> coll = { 1, 3, 19, 5, 13, 7, 11, 2, 17 }; cout << "all elements:" << endl; ContainerUtil<deque<int>>::printElements(coll); int x, y; cout << "Input x: "; cin >> x; cout << endl; cout << "Input y: "; cin >> y; cout << endl; auto pos = find_if(coll.cbegin(), coll.cend(), // range [=](int i) { // search criterion return i > x && i < y; }); cout << "first elem >"<< x <<" and <"<< y <<": " << *pos << endl;
[](double d) { // lambda as function object
return d*d*d;
});
看個簡單的例子:
findFirstInRange.cpp
運行結果:
all elements: 1 3 19 5 13 7 11 2 17
Input x: 5
Input y: 18
first elem >5 and <18: 13
注意點:
[=]
這個符號表明在lambda被聲明時已有效的所有符號都以傳值(by value)的形式傳入lambda體內
[&]
這個符號表明在lambda被聲明時已有效的所有符號都以傳引用(by reference)的形式傳入lambda體內
lambda內部可以改動他們的值
上面例子lambda的等價物
auto pos = find_if(coll.cbegin(), coll.cend(), // range
[=](int i) { // search criterion
return i > x && i < y;
});
它等價於
1. 手寫的循環
deque<int>::iterator pos; for (pos = coll.begin;pos!=coll.end(); ++pos) { if (*pos > x && *pos < y) { break; } }
2. predicate(判斷式)
bool pred(int I) { return I > x && I < y; } ... pos = find_if(coll.begin(), coll.end(), pred);
