Hi, I'm trying to write a method that returns true or false whether this element exists in my list.
Basically, I have a list of a struct.
1 2 3 4 5
struct Person
{
int age;
string name;
};
I have a list of persons.
std::list<Person> listPerson;
and I have the following method:
1 2 3 4 5 6 7
bool personExists(int age) const
{
auto list= listPerson;
auto it = find(list.begin(), list.end(), ?????);
return it != list.end();
}
At the ?????, I just want to check if in the list, there is a Person with x age.
Is there a way to use the std::find to do that or should I just manually code a for loop with a if statement?
std::find() uses operator == for comparison, so if your question specifically asked you to use std::find() and std::find() only - you could, by overloading this operator. Otherwise std::find_if() is certainly the way to go: