哈希表-哈希函数的实现

Hash table - hash function implementation

本文关键字:实现 函数 哈希 哈希表      更新时间:2023-10-16

我在这个项目中需要实现一个哈希表。我有两个班:球迷和门票。粉丝可以拥有门票,每张门票都与粉丝的电子邮件相关联。

我的问题是,什么是关键,我应该在哪里实现我的哈希函数?我猜它会在Ticket.h,但我仍然不知道如何将门票与粉丝(所有者)的电子邮件联系起来。

我认为不需要任何代码,但如果有任何疑问,我会发布一些。

致以最诚挚的问候

Class Fan("Adepto")

class Adepto {
int uid;
unordered_set<string> email;
static int newID;
string nome;
string nEquipa;

公用:

Adepto(string nome);
//Adepto(string nome, Equipa* e1, vector<Bilhete*> bilhetes);
Adepto();
unsigned int getID() const;
string getNome() const;
void setNome(string n);
string getEquipa() const;
void setEquipa(string nEq);
string getEmail() const;
void setEmail(string novoEmail);

票务等级(bilhette)

struct hash_adeptos{
int operator() (const Adepto &a1) const{
    return a1.getEmail()().size(); }
bool operator() (const Adepto & a1, const Adepto & a2) const{
    return a1.getEmail() == a2.getEmail();}
};

typedef tr1::unordered_set<Adepto, hash_adeptos, hash_adeptos> TabelaAdeptos;
 class Bilhete{
TabelaAdeptos adeptos;
int uid;
static int newID;
date validade;
string dono;
bool vendido;
 public:
Bilhete(date validade, string dono, bool vendido);
Bilhete();
int getID() const;
void setID(int id);
date getValidade() const;
void setValidade(date date);
string imprimeBilhete() const;
//Adepto* getDono() const;
//void setDono (Adepto &a1);
bool getEstado() const;
bool setVendido(Bilhete &b1);
};

我的问题是,的关键是什么

我认为关键是票。因此,您可以通过票号获取有关持票人的信息。

我应该在哪里实现我的散列函数

我认为这无关紧要。我可能会创建另一对文件:TicketHash.hppTicketHash.cpp

我仍然不知道如何将门票与粉丝(所有者)的电子邮件联系起来

哈希函数必须以票证为参数,并返回哈希表中单元格(或指向单元格的指针)的编号以及相应的票证持有者信息。

我认为您甚至可以制作这样的函数unsigned int hash(Ticket& ticket) { return ticket.number; },但它将只是一个数组,而不是哈希表。

有关散列函数的示例,请参阅以下问题

我会以以下方式实现这一点:

Class Tickets{
    String number;
    //Other details...
}
Class Fans{
    ArrayList<Tickets> list;
    String email;
    int index;      //this is an auto increment field which I'd have used in my implementation, just for the ease of further operations. This actually helps.
    //Other details
}
Class Hash{
    //KEY
    String[] key;    //index and email in `Fans` class are unique values
    //Value
    ArrayList<Tickets>[] value;
    //function to assign values
    void assign(String id, Ticket ticket){
        if(key.contains(id))
            value<index of id>.add(Ticket);
        else
            value<new index>.add(Ticket);
    }
    //function that returns value
    Arraylist<Tickets> value(String id){
        return value<index of id>;
    }
}

编辑:

很抱歉,我没有看到标签c++。我已经用类似JAVA的语法编写了它,但由于它是粗糙的逻辑,所以应该可以理解。如果有任何困惑,请在下面发表评论。您可以在cpp中使用vector<>list<>来代替ArrayList。