Is there a way to use stl algorithms like find() and find_if() in a container of objects? Ex.:With find() find the element whit name "abc" in a vector of class Alfhabetic.
2 Answers
You can define a comparing predicate (functor). Here is a generic implementation:
struct AlphabeticNameComp { AlphabeticNameComp( const std::string& toCompare) : toCompare_( toCompare) { } bool operator()( const Alphabetic& obj) const { return toCompare_ == obj.name(); } private: const std::string toCompare_; }; In a vector of Alphabetic elements
std::vector< Alphabetic> vect; you can run a search like:
std::find_if( vect.begin(), vect.end(), AlphabeticNameComp( "abc"));