Całkiem niedawno napisałem krótki artykuł, gdzie wykorzystałem koncepcję wyrażeń lambda i w oparciu o nie zbudowałem prosty system zdarzeń dla okienek Windows. Wyrażenia Lambda wprowadzone wraz z C++0x są na tyle uniwersalnie zbudowane, że z łatwością mogą być skonsumowane przez algorytmy ze standardowej biblioteki STL. Oto przykład z find_if:
Klasyczne wykorzystanie "zapożyczone" z www.cplusplus.com:
// find_if example
#include <iostream> #include <algorithm> #include <vector> using namespace std;
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool IsOdd (int i) { return ((i%2)==1); }
bool IsOdd (int i)
{
return ((i%2)==1);
}
int main () { vector<int> myvector; vector<int>::iterator it;
int main ()
vector<int> myvector;
vector<int>::iterator
it;
myvector.push_back(10); myvector.push_back(25); myvector.push_back(40); myvector.push_back(55); it = find_if (myvector.begin(), myvector.end(), IsOdd); cout << "The first odd value is " << *it << endl; return 0; }
myvector.push_back(10); myvector.push_back(25); myvector.push_back(40); myvector.push_back(55); it = find_if (myvector.begin(), myvector.end(), IsOdd); cout << "The first odd value is " << *it << endl; return 0;
Można równie dobrze skonstruować tak:
#include <iostream> #include <algorithm> #include <vector> #include <functional>using namespace std;
#include <functional>using namespace std;
myvector.push_back(10); myvector.push_back(25); myvector.push_back(40); myvector.push_back(55); it = find_if (myvector.begin(), myvector.end(), [](int n) { return ((i%2)==1); }); cout << "The first odd value is " << *it << endl; return 0; }
myvector.push_back(10); myvector.push_back(25); myvector.push_back(40); myvector.push_back(55); it = find_if (myvector.begin(), myvector.end(),
[](int n) { return ((i%2)==1); }); cout << "The first odd value is " << *it << endl; return 0;
Polecam potestować lambda również przy innych często wykorzystywanych algorytmach jak for_each, sort, lower_bound, upper_bound, count_if i innych, których używacie.Muszę przyznać, że z Boost'owymi elementami C++x0/TR1 można się w STLu zakochać na nowo.