开发者

Is the "==" operator required to be defined to use 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 both VS2010 and VS2005 the following does not compile:

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

complaining about lack of == operator.

I naively assumed it would do a value comparison of the myClass object's public members, but I am almost positive this is not correct.

I assume if I define a == operator or perhaps use a functor instead, it will solve the problem.

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

Is this right or should I 开发者_Python百科be doing something else?


The compiler does not automatically generate a default operator==(), so if you don't write one yourself, objects of your class can't be compared for equality.

If you want memberwise comparison on the public members you have to implement that yourself as operator==() (or "manually" use a separate function/functor to do the comparison).


Find does require the value to be equality comparable, and the compiler will not define you a default operator==.

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


std::find needs operator==. Even if the members are public, it doesn't necessarily mean that all of them are relevant in defining what equality means for this class.

If you don't want to overload the operator for some reason (e.g there is no one single intuitive meaning of equality for that class, instances could be consider equal in some respect or another), you can code a suitable function object and use std::find_if. For example:

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")); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜