2017-01-22 37 views
2

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

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

+0

你的'operator =='(和'operator!=')在哪里? – Toris

+1

自定义比较器用于比较集合中的元素,不用于比较集合 – Loreto

+0

这很有趣,但[this](http://ideone.com/tn1huh)起作用。不知道为什么,可能是编译器认为's'是一个函数。 – ilotXXI

回答

4

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

的密钥必须满足以使用过载(1-2)相等性的要求。

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

类型T满足相等性如果
给定一个,b和c,T型或const的表达t
以下表达式必须是有效的,并且具有其指定的效果:
a == b

因此,你ne编辑为IntWrapper类型定义operator==

+0

接受,但它没有意义我。为什么需要?我已经定义了一个比较小的比较,很容易从中获得平等。 – effeffe

+2

@effeffe等价!=平等。这些是不同的概念。如果你想设置等价性,你可以使用'not((a

+0

集合等价和集合相等有什么区别? – effeffe