Using "std::find" from the algorithm librairy for a list of struct?

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?

Thank you.
Last edited on
No and no.

The std::find uses a value. That is not convenient.

No need for loop, use std::find_if
http://www.cplusplus.com/reference/algorithm/find_if/
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

# include <iostream>
# include <algorithm>
# include <list>
# include <string>

struct Person
{
    int m_age;
    std::string m_name;

    bool operator == (const int age)const
    {
        return m_age == age;
    }
    Person (const int age, const std::string& name)
        : m_age(age), m_name(name){}
};


int main()
{
    std::list<Person> personsList{};
    personsList.emplace_back(42, "john");
    personsList.emplace_back(24, "jane");

    if (std::find(personsList.cbegin(), personsList.cend(), 42) != personsList.cend())
    {
        std::cout << "found \n";
    }
    else
    {
        std::cout << "not found \n";
    }
}

Oh thanks guys. I didn't look into the find_if.
Cheers!"
auto list= listPerson;
I believe this makes a copy of the list. That would be very inefficient.
Topic archived. No new replies allowed.