2

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 2

7

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"));
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.