无法将std :: unorded_set与自定义KeyEqual进行比较 [英] Can not compare std::unorded_set with custom KeyEqual
问题描述
以下程序无法编译.但是,如果我不注释 operator ==
,它就会编译.当我已经提供了 FooEqual
The following program does not compile. But If I do not comment out operator==
, it compiles. Why operator==
is still needed when I already provide FooEqual
#include <cstddef>
#include <unordered_set>
struct Foo {
};
struct FooHasher {
size_t operator()(const Foo&) const {
return 1;
}
};
struct FooEqual {
bool operator()(const Foo& lhs, const Foo& rhs) const {
return true;
}
};
// bool operator==(const Foo& lhs, const Foo& rhs) {
// return true;
// }
int main() {
std::unordered_set<Foo, FooHasher, FooEqual> s1;
std::unordered_set<Foo, FooHasher, FooEqual> s2;
(void)(s1 == s2);
return 0;
}
推荐答案
"23.2.5无序关联容器"状态:
"23.2.5 Unordered associative containers" states:
如果a.size()== b.size(),则两个无序容器a和b比较相等并且,对于从中获得的每个等效键组[Ea1,Ea2)a.equal_range(Ea1),存在一个等效密钥组[Eb1,Eb2)从b.equal_range(Ea1)获得,从而距离(Ea1,Ea2)==distance(Eb1,Eb2)和is_permutation(Ea1,Ea2,Eb1)返回true.
Two unordered containers a and b compare equal if a.size() == b.size() and, for every equivalent=key group [Ea1,Ea2) obtained from a.equal_range(Ea1), there exists an equivalent-key group [Eb1,Eb2) obtained from b.equal_range(Ea1), such that distance(Ea1, Ea2) == distance(Eb1, Eb2) and is_permutation(Ea1, Ea2, Eb1) returns true.
将其剥离,归结为根据 std :: is_permutation()
定义的无序容器的相等性.
Stripping this down, it all comes down to the equality of unordered containers being defined in terms of std::is_permutation()
.
重要的是,它引用了 std :: is_permutation
()的三个参数形式,而不是四个参数形式!
The important part is that this references the three argument form of std::is_permutation
(), and not the four argument form!
换句话说,对于无序容器的内容,而不是容器的官方比较功能,整个纸牌屋最终被缩减为默认的 operator ==
.
In other words, the whole house of cards ends up being reduced to the default operator==
, for the contents of the unordered container, rather than the container's official comparison function.
这是我的读物.
这篇关于无法将std :: unorded_set与自定义KeyEqual进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!