微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用于存储类对象的 C++ 哈希表

如何解决用于存储类对象的 C++ 哈希表

我见过很多字符串或整数值的哈希表实现。但是,我需要有关如何将对象作为值存储在哈希表中的帮助。我创建了一个 Book 类,需要将它的实例存储到一个哈希表中。我怎么做 ? 下面是我使用单独链接避免冲突的哈希表实现。

...

#ifndef HASH_H_
#define HASH_H_

#include <string>
#include <iostream>

using namespace std;

class hashtable{
  private:
    static const int tablesize = 10;

    struct book{
        string name;
        string author;
        book* next;
    };

book* HashTable[tablesize];



public:
    hashtable();
    int Hash(string key);
    void Add(string key,string author);
    int num(int index);
    void PrintTable();
    void PrintItems(int index);
};

#endif


hashtable::hashtable(){
  for(int i=0; i<tablesize; i++){
    HashTable[i] = new book;
    HashTable[i]->name = "empty";
    HashTable[i]->author = "empty";
    HashTable[i]->next = NULL;
  }
}

void hashtable::Add(string name,string author){
  int index = Hash(name);
  if (HashTable[index]->name == "empty"){
    HashTable[index]->name = name;
    HashTable[index]->author = author;
  }else{
    book* Ptr = HashTable[index];
    book* n = new book;
    n->name = name;
    n->author = author;
    n->next = NULL;
    while (Ptr->next != NULL){
      Ptr = Ptr->next;
    }
    Ptr->next = n;
  }
}
...

解决方法

使用地图,但您需要使用一些东西作为哈希。也许书名?

std::map<std::string,Book> bookMap;

然后您可以通过以下方式访问图书:

bookMap["Flowers for Algernon"]

插入有点棘手。

ptr = bookMap( pair<string,Book>("The Old Man of the Sea",myBook) );

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。