首页 > 解决方案 > 用于存储类对象的 C++ 哈希表

问题描述

我已经看到大量用于字符串或 int 值的哈希表实现。但是,我需要有关如何将对象作为值存储在哈希表中的帮助。我创建了一个 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;
  }
}
...

标签: c++arrayshashtable

解决方案


使用地图,但你需要一些东西来用作散列。也许书名?

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

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

bookMap["Flowers for Algernon"]

插入有点棘手。

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

推荐阅读