使用自定义比较函数设置相等性

Set equality with custom compare function

我正在使用用户定义类型集和自定义比较函数。当我尝试在集合之间使用 == 运算符时,出现编译时错误。我错过了什么?

#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.

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

因此,您需要为 IntWrapper 类型定义 operator==