Christian Benincasa
Christian Benincasa

Reputation: 1215

Searching for string in vector of pointers

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.

Upvotes: 1

Views: 1392

Answers (2)

Nim
Nim

Reputation: 33655

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.. :)

Upvotes: 1

Diego Sevilla
Diego Sevilla

Reputation: 29011

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...

Upvotes: 4

Related Questions