1

I understand how to find a specific value in a vector using
find(vector.begin(), vector.end(), item)!=vector.end()
however, I have a vector of pointers which points to objects of type Restaurant and I need to be able to search this vector for an attribute of the objects each element points to.

I'm not sure if I can construct a call to the vector's .find() method to get this down, or if I need I need to find another way to do this.

The call from the vector to find the name of a restaurant using the class is (restaurantPointerVector[i])->getRestaurantName()
but I need to know how to search through this attribute to return whether or not a Restaurant object with the name I am searching for already exists in the vector.

2 Answers 2

4

find_if is your friend. Here is an example:

struct Comparator {
   const char* expected_name;

   Comparator(const char* _expected_name) 
     : expected_name(_expected_name)
   {}

   bool operator()(const Restaurant* r1) const
   { return !strcmp(r1->getRestaurantName(), expected_name); } // Just an example using strcmp
};

then:

find_if(vector.begin(), vector.end(), Comparator("Searched Restaurant Name"));

Of course, this is much nicer with C++0x...

1
  • You should make operator() const.
    – ildjarn
    May 26, 2011 at 22:12
1

Step by step.

  1. Construct a functor (function object) which takes during construction the value of the attribute you are searching by. Ensure that the operator() is implemented correctly to accept a pointer to the object in the vector.

  2. in the operator check the attribute against the value, and return the matching state

  3. call std::find_if with this function object.

EDITED: per @ildjarn's comment! :) now am definitely off to bed.. :)

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.