0

Possible Duplicate:
How to find an item in a std::vector?

Given these two classes:

class Book
{
private:

  string title;
  int category;

public:

  Book(const string& , int num);
}

Book(const string& name, int num)
  :title(name), category(num)
{ }



class Reader
{
private:

string reader_name;
vector <Book> bookLists;

public:

void add(const Book &ref);
};

void add(const Book& ref)
{
    // My problem is here.
}

I want to search inside the vector of Book. If the Book is in the vector of Book, it does nothing. If the Book is not in the vector of Book bookLists.push_back(ref);

Community
  • 1
  • 1
newb
  • 1
  • 2
  • You might find [this question](http://stackoverflow.com/questions/571394/how-to-find-an-item-in-a-stdvector) useful. – Diederik May 29 '11 at 08:07

2 Answers2

1

You should use:

std::find(bookLists.begin(), bookLists.end(), bookItemToBeSearched)!=bookLists.end().

std::find returns:
An iterator to the first element in the range that matches value OR
If no element matches, the function returns last.

Check more about the std::find algorithm here.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
0
void add(const Book& ref)
{
   if(std::find(bookLists.begin(), bookLists.end(), ref)==bookLists.end())
   {
       bookLists.push_back(ref);
   }
}
Norbert
  • 4,239
  • 7
  • 37
  • 59
  • Thank you! Do I need to state any vector iterator?? – newb May 29 '11 at 08:03
  • You will need to define Book::operator== for this to work, since std::find cannot "guess" on what criteria you want to compare the books (are the titles sufficient ? do they actually need to be the same physical object ?). For example, you could define bool Book::operator==(const Book &other) const { return title == other.title && category == other.category; } – ZeRemz May 29 '11 at 08:20
  • Thank you ZeRemz. I didn't know I have to define Book::operator== that's why I was keep getting compiline error – newb May 29 '11 at 08:29