Does the "==" operator require std :: find

Let's say I have:

class myClass
std::list<myClass> myList

      

where myClass does not define the == operator and only consists of public fields.

In VS2010 and VS2005, the following does not compile:

myClass myClassVal = myList.front();
std::find( myList.begin(), myList.end(), myClassVal )

      

complains about the absence of the == operator.

I naively assumed that it would perform a comparison on the values ​​of the public elements of the myClass object, but I'm pretty sure this is not true.

My guess is that if I define the == operator, or maybe use a functor, it solves the problem.

Alternatively, if my list had pointers instead of values, the comparison would work.

Is this correct or should I be doing something else?

+2


a source to share


3 answers


The compiler doesn't automatically generate by default operator==()

, so if you don't write it yourself, objects in your class cannot compare for equality.



If you want the comparison to still be exposed to public members, you must implement it as operator==()

(or "manually" use a separate function / functor to perform the comparison).

+7


a source


Find requires that the value is equal to comparable , and the compiler will not figure you out by default operator==

.



Alternatively, you can use find_if and provide a functor predicate.

+5


a source


std::find

required operator==

. Even though the members are public, it doesn't necessarily mean that they all have to do with defining what equality means for that class.

If you don't want to overload the operator for any reason (for example, there is no single intuitive value for equality for this class, instances can be considered equal in one way or another), you can code a suitable function object and use std::find_if

. For instance:

struct same_surname_as
{
    Person p;
    same_surname_as(const Person& x): p(x) {}
    bool operator()(const Person& person) const { return p.surname == person.surname; }
};

list<Person> li;
find(li.begin(), li.end(), same_surname_as(Person("Pu Songling")); 

      

+3


a source







All Articles