为什么unordered_set的元素对于自定义eslore_to不是唯一的
我试图更好地理解unordered_set。主要是我在unordered_set中的理解元素应该是唯一的,直到相等的_to操作员。 因此,我决定通过一小部分代码来测试
#include <iostream>
#include <unordered_set>
using namespace std;
struct m_int
{
int x;
};
// template specialization for std::hash
template<>
struct std::hash<m_int>
{
std::size_t operator()(m_int const& x) const noexcept
{
return hash<int>{}(x.x);
}
};
//template specialization for std::equal_to
template<>
struct std::equal_to<m_int>
{
bool operator()(const m_int &lhs, const m_int &rhs) const
{
return abs(lhs.x-rhs.x)<=3;
}
};
int main() {
unordered_set<m_int> m={{1},{2},{3},{4}};
for(auto&x:m)
cout<<x.x<<' ';
cout<<endl;
cout<<m.count({2})<<endl;
// your code goes here
return 0;
}
我最初的想法是将1插入2,而3将插入4。
我得到的输出是
4 3 2 1
1
因为根据我的等效_to 1和2是相同的,因此该集合实际上包含重复,这与集合的定义相对。为什么这种情况呢?我该如何解决?
I am trying to understand unordered_set better. Mainly, to my understanding elements in an unordered_set should be unique up to equal_to operator.
Therefore, I decided to test that by a small piece of code
#include <iostream>
#include <unordered_set>
using namespace std;
struct m_int
{
int x;
};
// template specialization for std::hash
template<>
struct std::hash<m_int>
{
std::size_t operator()(m_int const& x) const noexcept
{
return hash<int>{}(x.x);
}
};
//template specialization for std::equal_to
template<>
struct std::equal_to<m_int>
{
bool operator()(const m_int &lhs, const m_int &rhs) const
{
return abs(lhs.x-rhs.x)<=3;
}
};
int main() {
unordered_set<m_int> m={{1},{2},{3},{4}};
for(auto&x:m)
cout<<x.x<<' ';
cout<<endl;
cout<<m.count({2})<<endl;
// your code goes here
return 0;
}
My initial thought is that 1 would be inserted 2, and 3 would but 4 would be inserted.
The output I got was
4 3 2 1
1
since according to my equal_to 1 and 2 are the same, then this set actually contains repetition, which is against the definition of the set. Why is that the case and how can I solve that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
未排序的容器具有以下对其哈希和密钥平等函数的要求:
对于您的容器而言,这是不正确的。例如,1和4比较平等,但它们(几乎可以肯定)具有不同的哈希值。这导致不确定的行为。
这里的另一个逻辑问题:1等于4,4等于7,但1不等于7。这也不计算。
Unordered containers have the following requirements for their hash and key equality functions:
This is not true for your container. 1 and 4, for example, compare equal but they'll (almost certainly) have different hash values. This results in undefined behavior.
Another logical problem here: 1 is equal 4, and 4 is equal to 7, but 1 is not equal to 7. This does not compute, either.