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.
+7
A:
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"));
Cătălin Pitiș
2009-04-20 16:32:39
+1
A:
You can define an operator==()
for class Alfhabetic
that matches only the data member abc
something like that:
bool operator==(const Alfhabetic& a, const Alfhabetic& b)
{
return (a.abc == b.abc);
}
and then finding an Alfhabetic
instance initialized with abc
as the value you want.
shoosh
2009-04-20 16:32:45