Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ How to make find_if not only return the first object for which applying pred to it is true

Tags:

c++

algorithm

stl

This is meant to allow user to input name, contact and address he/she wishes to search for. What I wanted to do is to display all objects that applying pred to it is true but I can't seems to get it working.

static string searchName, searchContact, searchAddress;

bool search_User(User &u)
{ 
   return (u.getName() == searchName && u.getContact() == searchContact && u.getAddress() == searchAddress);

}
void searchUser(vector<User> &u)
{
    cout << "Name of user: ";
    getline(cin, searchName);
    cout << "Contact of tutor: ";
    getline(cin, searchContact);
    cout << "Adress of user: ";
    getline(cin, searchAddress);
    vector<User>::iterator i;
    i = find_if(u.begin(), u.end(), search_User);
    cout << i->getName() << i->getContact() << i->getAddress() << endl;
}
like image 670
delphi316 Avatar asked Nov 23 '25 19:11

delphi316


2 Answers

The usual solution is to use std::copy_if:

std::vector<User> matches;
std::copy_if(v.begin(), v.end(), std::back_inserter(matches),
    [Name, Contact, Address](User const& u)
    { return u.getName() == Name && u.getContact() == Contact && u.getAddress() == Address;});

or just write a classic loop

for (User& u : users) {
  if (search_User(u) {
    std::cout << u; // Assumes you've implemented operator<<(ostream&, User)
  }
} 
like image 144
MSalters Avatar answered Nov 26 '25 09:11

MSalters


Pseudocode:

for(iterator i = v.begin(); 
    (i = find_if(i, v.end(), ...)) != v.end(); ++i )
{
    print *i;
}
like image 30
Armen Tsirunyan Avatar answered Nov 26 '25 09:11

Armen Tsirunyan