【发布时间】:2017-06-07 06:59:51
【问题描述】:
我正在使用一组用户定义的类型和一个自定义比较函数。当我尝试在集合之间使用 == 运算符时,我得到一个编译时错误。我错过了什么?
#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
}
【问题讨论】:
-
你的
operator==(和operator!=)在哪里? -
自定义比较器用于比较集合中的元素,而不是用于比较集合
-
这很有趣,但this 有效。不知道为什么,可能是编译器认为
s是一个函数。 -
@ilotXXI 也许比较指针。
-
@Toris 但需要吗?
std::set只需要一个小于比较,从中很容易得到相等性检查;否则,根本无法构造该集合,因为它需要相等才能检查重复项。
标签: c++ stl set operators equality