开发者

SEARCH or FOUND inside of vector problem [duplicate]

开发者 https://www.devze.com 2023-03-09 14:25 出处:网络
This question already has answers here: Closed 10 years ago. Possible D开发者_JS百科uplicate: How to find an item in a std::vector?
This question already has answers here: Closed 10 years ago.

Possible D开发者_JS百科uplicate:

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);


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.


void add(const Book& ref)
{
   if(std::find(bookLists.begin(), bookLists.end(), ref)==bookLists.end())
   {
       bookLists.push_back(ref);
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号