Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set equality with custom compare function

I am using sets of user-defined types and a custom compare function. When I try to use the == operator between sets I get a compile-time error. What am I missing?

#include <cassert>
#include <set>

// my user-defined type
struct IntWrapper {
    int value;
};

// my compare function
struct LessComparer {
    bool operator()(const IntWrapper& lhs, const IntWrapper& rhs) const {
        return lhs.value < rhs.value;
    }
};

int main() {
    std::set<IntWrapper, LessComparer> s;
    assert(s == s);  // I would expect this to work
}

Here you can see the error.

like image 630
effeffe Avatar asked Sep 10 '26 06:09

effeffe


1 Answers

http://en.cppreference.com/w/cpp/container/set/operator_cmp

Key must meet the requirements of EqualityComparable in order to use overloads (1-2).

  http://en.cppreference.com/w/cpp/concept/EqualityComparable

The type T satisfies EqualityComparable if
Given a, b, and c, expressions of type T or const T
The following expressions must be valid and have their specified effects:
a == b

So, you need to define operator== for IntWrapper type.

like image 83
Revolver_Ocelot Avatar answered Sep 12 '26 19:09

Revolver_Ocelot