用于哈希的哈希集函数

Hash set function for hashing

本文关键字:哈希 集函数 用于      更新时间:2023-10-16

我试图实现一个哈希集,但我有一些麻烦的哈希函数。我想在集合中添加姓名和电话号码:

class Person{
    string name;
    long long int phoneNumber;
}

集合中的索引是通过对phoneNumber的数字求和来计算的。问题是我不希望我的函数是这样的:

int add(long long int nr, Element e) - the function that adds an Element to the set
{
     int hashCode = hash(nr);;
     ...
}

,其中long long int nr应为phoneNumber, Element e应为Person。我是说,这很愚蠢。如果我已经有person作为参数,为什么还要有phoneNumber呢?正如您所看到的,我正在使用模板,我的老师建议我为hashFunction做一个虚拟类,以强制它成为各自的类型(类似于Java中的HashSet)。问题是我不知道该怎么做。你有什么可以帮助我的主意吗?

如果你这样做了:

 int add(Person p, Element e)

你将限制你的hasset类完全依赖于Person类。以这种方式将整数或字符串值放入哈希方法中更合理。您可以在散列方法之外确定要散列的参数,并将其作为输入。

此外,当您向Person类添加另一个成员(如age)并在散列中使用in时,您还需要修改散列方法以使用该特定成员