Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use lambda for std::find_if

Tags:

c++

lambda

stl

I am trying to use std::find_if to find an object that matches some criteria. Consider the following:

struct MyStruct         
{
    MyStruct(const int & id) : m_id(id) {}                      
    int m_id;
};
...         
std::vector<MyStruct> myVector; //... assume it contains things

MyStruct toFind(1);
std::vector<MyStruct>::iterator i = std::find_if(myVector.begin(), myVector.end(), ???);

I am not sure what to put in the ???

All the examples I have seen have a lambda that uses a hard-coded value to check for the ID. What I want is to return the iterator/success only if the id of toFind matches the id of one of the items in the vector.

All the examples I have see don't show me how to pass the two parameters

EDIT

Additional info There are two different scenarios I have to use this for One in which there is an == operator for the struct and another in which there is no operator == for the struct - and i can't create one because the criteria for finding a match for this scenario is not as rigid as would be used for an equivalence operator.

(And thanks to all who responded; I was able to use find() in one case and with your help was able to use find_if() for the other)

like image 798
Tim Avatar asked Mar 21 '17 17:03

Tim


People also ask

Can std :: function store lambda?

Instances of std::function can store, copy, and invoke any CopyConstructible Callable target -- functions, lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.

Is a lambda a std :: function?

Lambda's type One important thing to note is that a lambda is not a std::function .

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.

How do lambdas work C++?

A lambda can introduce new variables in its body (in C++14), and it can also access, or capture, variables from the surrounding scope. A lambda begins with the capture clause. It specifies which variables are captured, and whether the capture is by value or by reference.


1 Answers

Try this:

std::find_if(
    myVector.begin(), myVector.end(),
    [&toFind](const MyStruct& x) { return x.m_id == toFind.m_id;});

Alternatively, if you had defined an appropriate == overload for MyStruct, you could just use find:

std::find(myVector.begin(), myVector.end(), toFind);  // requires ==

The find_if version is usually best when you have some kind of heterogeneous lookup, for example if you were just given an int, not a value of MyStruct.

like image 73
Kerrek SB Avatar answered Sep 21 '22 11:09

Kerrek SB