为什么unordered_set的元素对于自定义eslore_to不是唯一的

发布于 2025-01-31 13:20:55 字数 995 浏览 2 评论 0原文

我试图更好地理解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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

少跟Wǒ拽 2025-02-07 13:20:55

未排序的容器具有以下对其哈希和密钥平等函数的要求

如果两个键相等,则哈希必须返回相同的
两个键的值。

对于您的容器而言,这是不正确的。例如,1和4比较平等,但它们(几乎可以肯定)具有不同的哈希值。这导致不确定的行为。

这里的另一个逻辑问题:1等于4,4等于7,但1不等于7。这也不计算。

Unordered containers have the following requirements for their hash and key equality functions:

If two Keys are equal according to Pred, Hash must return the same
value for both keys.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文