How to use lambda for std::find_if

后端 未结 4 909
情书的邮戳
情书的邮戳 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: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.

提交回复
热议问题