Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ find_if lambda

Tags:

c++

lambda

What is wrong with the code below? It is supposed to find an element in the list of structs if the first of the struct's members equals to 0. The compiler complains about the lambda argument not being of type predicate.

#include <iostream> #include <stdint.h> #include <fstream> #include <list> #include <algorithm>  struct S {     int S1;     int S2; };  using namespace std;  int main() {     list<S> l;     S s1;     s1.S1 = 0;     s1.S2 = 0;     S s2;     s2.S1 = 1;     s2.S2 = 1;     l.push_back(s2);     l.push_back(s1);      list<S>::iterator it = find_if(l.begin(), l.end(), [] (S s) { return s.S1 == 0; } ); } 
like image 255
Daniel Avatar asked Nov 15 '12 08:11

Daniel


People also ask

Does C have Lambda Expression?

No, C doesn't have lambda expressions (or any other way to create closures). This is likely so because C is a low-level language that avoids features that might have bad performance and/or make the language or run-time system more complex.

What does Find_if return?

C++ Algorithm find_if() function returns the value of the first element in the range for which the pred value is true otherwise the last element of the range is given.

Why do we need lambda expressions in C++?

One of the new features introduced in Modern C++ starting from C++11 is Lambda Expression. It is a convenient way to define an anonymous function object or functor. It is convenient because we can define it locally where we want to call it or pass it to a function as an argument.

What is Lambda Expression in C++?

C++ Lambda expression allows us to define anonymous function objects (functors) which can either be used inline or passed as an argument. Lambda expression was introduced in C++11 for creating anonymous functors in a more convenient and concise way.


1 Answers

Code works fine on VS2012, just one recommendation, pass object by reference instead of pass by value:

list<S>::iterator it = find_if(l.begin(), l.end(), [] (const S& s) { return s.S1 == 0; } ); 
like image 164
billz Avatar answered Oct 04 '22 20:10

billz