How to use lambda for std::find_if

后端 未结 4 908
情书的邮戳
情书的邮戳 2021-02-07 22:33

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         


        
相关标签:
4条回答
  • 2021-02-07 22:52

    This is where the lambda capture comes into play. Besides saying what type of parameters are to be passed to the lambda you can also say what existing variables are to be used to construct the lambda with. So in this case you would have something like

    std::vector<MyStruct>::iterator i = std::find_if(myVector.begin(),
        myVector.end(), 
        [&](const auto& val){ return val.m_id == toFind.m_id; } );
    

    So the [&] says capture all variables used in the body of the lambda by reference. The (const auto& val) makes the operator() of the lambda a template and lets you take in any type. Then in the body we compare what is passed in from find_if to toFind.

    0 讨论(0)
  • 2021-02-07 22:59

    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.

    0 讨论(0)
  • 2021-02-07 23:06

    Do as following:

    std::find_if(myVector.begin(), myVector.end(), 
              [&toFind] (const auto &ele) { return ele.m_id == toFind.m_id}; );
    
    0 讨论(0)
  • 2021-02-07 23:11

    You may use the following:

    MyStruct toFind(1);
    std::vector<MyStruct>::iterator i =
        std::find_if(myVector.begin(), myVector.end(),
                     [&](const auto& e) { return e.id == toFind.id; });
    
    0 讨论(0)
提交回复
热议问题