哈希表 - 哈希函数实现

时间:2015-12-18 13:21:40

标签: c++ algorithm data-structures hashtable

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

我的问题是,什么是关键,我应该在哪里实现我的哈希函数?我的猜测是它会在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);

门票类(bilhete)

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);
};

2 个答案:

答案 0 :(得分:0)

  

我的问题是,什么是关键

我认为钥匙是票。因此,您可以按票号获取有关持票人的信息。

  

我应该在哪里实现我的哈希函数

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

  

我仍然不知道如何将此门票与粉丝(所有者)电子邮件相关联

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

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

有关散列函数的示例,请参阅this question

答案 1 :(得分:0)

我已通过以下方式实现了这一点:

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-Like语法编写了它,但由于它是粗略的逻辑,它应该是可以理解的。如果有任何混淆,请在下面发表评论。代替ArrayList,您可以在cpp。

中使用vector<>list<>