Search for a struct item in a vector by member data

后端 未结 4 1551
后悔当初
后悔当初 2020-11-29 03:36

I\'m very new to c++ and I\'m trying to find a way to search a vector of structs for a struct with a certain member data.

I know this would work with simple types in

4条回答
  •  迷失自我
    2020-11-29 04:03

    If you want to find an element in STL container, use std::find or std::find_if algorithms With C++03, you need to overload operator== for std::find

    bool operator==(const Friend& lhs, const Friend& rhs)
    {
      return lhs.ID == rhs.ID;
    }
    
    if (std::find(friends.begin(), friends.end(), item) != friends.end())
    {
       // find your friend
    }
    

    OR C++11 with lambda:

    std::find_if(friends.begin(), friends.end(),  [](Friend& f){ return f.ID == "1"; } );
    

    If you want to remove a certain element, use std::remove_if

    std::remove_if(friends.begin(), friends.end(), 
          [](Friend& f){ return f.ID == "1"; });
    

提交回复
热议问题