yk1904
yk1904

Reputation: 1

C++ hash table for storing objects of a class

I've seen plenty of hash table implementation for string or int value. But, i need help on how to store objects as a value in a hash table. I created a Book class and need to store its instances into a hash table. How do i do that ? Below is my hash table implementation using separate chaining to avoid collision.

...

#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;
  }
}
...

Upvotes: 0

Views: 1241

Answers (1)

Joseph Larson
Joseph Larson

Reputation: 9068

Use a map, but you'll need something to use as the hash. Book name perhaps?

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

You could then access books with:

bookMap["Flowers for Algernon"]

Insertions are a little tricky.

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

Upvotes: 1

Related Questions