Demande d'explication de code std::find_if
Bonjour a tous,
Je cherchais comment utiliser la fonction std::find_if en comparant le membre d'un objet avec une valeur précise.
je suis tomber sur ce code en anglais :
Citation:
That's not how predicates work. You have to supply either a free function bool Comparator(const MyClass & m) { ... }, or build a function object, a class that overloads operator():
Code:
1 2 3 4 5 6 7 8 9
| struct MyClassComp
{
explicit MyClassComp(int i) n(i) { }
inline bool operator()(const MyClass & m) const { return m.myInt == n; }
private:
int n;
};
std::find_if(v.begin(), v.end(), MyClassComp(5)); |
In C++0x:
Code:
1 2
| std::find_if(v.begin(), v.end(),
[](const MyClass & m) -> bool { return m.myInt == 5; }); |
This captureless lambda is in fact equivalent to a free function. Here is a capturing version that mimics the predicate object:
Code:
1 2 3
| const int n = find_me();
std::find_if(v.begin(), v.end(),
[n](const MyClass & m) -> bool { return m.myInt == n; }); |
J'ai compris le première exemple de code c'est ce que j'ai choisie d'utiliser. Mais le second extrait la j'arrive plus à lire le code. Quelqu'un pourrais m'indiquer quel élément du C++11 est utilisé ici ?
Cordialement.