【问题标题】:how to write a customize hash function for unordered set which defined in the customize structure?如何为自定义结构中定义的 unordered_set 编写自定义哈希函数?
【发布时间】:2018-06-07 17:49:12
【问题描述】:

我正在尝试为我自己的结构编写一个新的哈希函数。这是我的代码:

struct people{
    int id;
    unordered_set<people>friends;
    people(int x) : id(x) {}
};

我需要一个散列函数给朋友,比如:

struct peopleHash{
    size_t operator()(const people& p) const{
        return p.id;
    }
}

问题来了:如果我先初始化 people,peopleHash 函数会找到“未定义类型的 people”。如果我先初始化 peopleHash,也会发生同样的事情。我试图在 people 结构中定义 peopleHash,例如:

struct people{
    int id;
    struct peopleHash{
        size_t operator()(const people& p) const{
            return p.id;
        }
    };
    unordered_set<people, peopleHash>friends;
    people(int x) : id(x) {}
};

但是编译器说:

error: invalid operands to binary expression ('const people' and 'const people')
        {return __x == __y;}

我不知道如何处理这个...有什么帮助吗?

【问题讨论】:

  • 实现people::operator==。如果两个实例具有相同的哈希值,则将它们进行相等性比较。
  • 您遇到的不仅仅是散列问题。无序容器中的类也必须实现==操作符,并且容器中的类必须是完整的类型,直到people的定义完成才能发生。这不仅仅是一个循环依赖问题,它本身可以通过前向声明轻松解决。
  • @Praetorian 感谢您的回复!我添加了 operator==,但它显示错误:重载的 'operator==' 必须是二元运算符(有 3 个参数)...我不明白... bool operator == (const people& x, const people& y){ 返回 x.id == y.id; }
  • 去掉第二个参数const people&amp; y,比较x.idthis-&gt;id。或者将运算符移到struct people {...}; 定义之外。

标签: c++ c++11 hash unordered-set


【解决方案1】:

你不能那样做。当您实例化 std::unordered_set 时,people 将是一个不完整的类型,这是未定义的行为。见http://eel.is/c++draft/library#res.on.functions

【讨论】:

  • Ummm.. 但是我需要一个描述这个人的 id 和他的朋友的类型,我需要检查他和他的朋友是否有一些共同的朋友。如果我使用向量而不是集合,每次我都必须遍历整个向量才能找到交点,这将非常耗时......有没有更好的解决方案?
猜你喜欢
  • 2020-08-27
  • 2012-11-09
  • 2019-06-13
  • 1970-01-01
  • 1970-01-01
  • 2015-03-23
  • 2011-12-17
  • 2020-06-23
  • 1970-01-01
相关资源
最近更新 更多