Newbie2018
Newbie2018

Reputation: 47

Use find_if and remove_if in a vector of struct C++

I have a program, with a struct filled with information of different persons. And a vector persons, with it.

struct Person
{
    std::string fName;
    std::string lName;
    float  length;
    std::string nSignature;

    bool operator==(const Person& m) const {
        return ((m.fName == fName) && (m.lName == lName) && (m.length == length) && (m.nSignature == nSignature));
    }
};

Now what I am trying to do is, to use find_if and search for a nSignature that is in the struct. And if it is, to print out all the elements that are connected to it.

Example:

Firstname: John Surname: Doe Length: 1,78m Signature: johdoe

Now if i search for johdoe, and it is found, i want to print out all the details (like abow) that are connected to signature johdoe.

But that is not the main problem right now, the main problem is that i cant get my search to work.

void searchName(vector<Person> &persons)
{
    string nameToFind;
    cout << "Search" << flush;
    cin >> nameToFind;

    auto findIt = find_if(persons.begin(), persons.end(), [&nameToFind](Person& person) {
        return person.nSignature == nameToFind;
    });

    if (findIt != persons.end()) 
        cout << findIt << endl;

}

It doesn't find anything, and doesn't return anything either.

Have I misunderstood find_if and the use of operators?

Upvotes: 0

Views: 547

Answers (1)

phy nju
phy nju

Reputation: 289

your code should work, and will find the first right signature.

The only problem is you need dereference the iterator, and also overload the operator << for your class.

cout << *findIt << endl;

or if you do not want to overload, you can cout what you want explicitly

cout << findIt->fName << " " << findIt->lName  << endl;

overload like such, then it will work well.

ostream& operator<<(ostream& os, const Person& p)  
{  
    os << p.fName << " " << p.lName << " " << p.length << " " << p.nSignature << endl;
    return os;  
}  

Upvotes: 1

Related Questions