Search code examples
c++lambdastl-algorithm

Using std::any_of with lambda calling overloaded equality operator


I have the following class:

Class Foo {
public:
    bool operator ==(const Foo& f);
    ...
private:
    set<pair<int,int>> points;
    ...
}

The overloaded equality operator returns true if two Foo objects have equal sets of points. It works as expected if I use it as such:

Foo a = Foo();
Foo b = Foo();
if (a == b) ...

My question is, why does the following fail to compile?

vector<Foo> foos = ...
Foo c = ...
if (any_of(foos.begin(),foos.end(),[c](const Foo& f) { return (f == c); }))
{
    // stuff
} 

Solution

  • In your lambda, f is const. So you can't call your operator== on it, because your operator== is not const. So fix that:

    bool operator==(const Foo& f) const;