You do not necessarily have to overload an operator in your class. Here is why: You already use std::list
. That's good. Now go one step further and also ditch your self-made algorithm in favour of the standard one: std::find_if
.
std::find_if
can search a standard container class using a comparison functor provided by you. Often, that functor is a struct
with an overloaded operator()
(so objects of it can be used like functions).
I'll give you an example:
#include <algorithm> // for std::find_if
// ...
struct CountryComparison
{
CountryComparison(std::string const &country) : m_country(country) {}
bool operator()(Nation const &nation) const
{
return nation.pays == m_country;
}
std::string m_country;
};
void modifierContinent(list<Nation> &liste, string const &nomPays, short nouveauContinent)
{
list<Nation>::const_iterator find_iter = std::find_if(liste.begin(), liste.end(),
CountryComparison(nomPays));
if (find_iter != liste.end())
{
cout << "found!";
}
}
I've also made sure strings are passed by const&, which should be the default for string arguments at least pre-C++11. And I pass liste
by &, which is also more likely the intended behaviour (as it does not create needless copies).
By the way, your Nation
class is strange. It contains a "country" (pays) and a "town" (ville). This means that in your class design, a nation consists of a country and a town. That doesn't make sense, except maybe for city states ;)
Edit: I forgot an implementation detail. As the functor cannot directly access the pays
member of Nation
, consider giving your class a member function like:
std::string GetPays() const
{
return pays;
}
Or make the functor a friend
of Nation
.