Hey everybody,
Could somebody please provide an example for using the STL find_if for the following task. I am trying to search a vector of structs, using the following criteria: compare whether the key of the struct in the vector matches the key of another struct (instace of the same type of struct) that I want to find. So basically search the vector for a particular struct. I want to use find_if, in order to replace the handwritten routine I have now. I have seen many complex, examples online. If anybody knows of simple and clean way, please share. Thanks in advance.

10 Years
Discussion Span
Last Post by vijayan121
#include <vector>
#include <algorithm>

struct some_struct { int key ; /* ... */ };

struct has_same_key
  explicit ( const some_struct& s ) : what(s) {}
  bool operator() ( const some_struct& elem ) const
  { return elem.key == what.key ; }
  const some_struct& what ;

inline std::vector<some_struct>::const_iterator 
   do_find( const std::vector<some_struct>& vec, const some_struct& what )
  return std::find_if( vec.begin(), vec.end(), has_same_key(what) ) ;
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.