Make a hash table using smart pointers?

I'm trying to make a hash table using smart pointers, but I'm not sure if I'm doing it right. I tried to play with two combinations of them, but I'm afraid I don't know how to initialize the table to be empty? It might not be the right option, but I'm stuck and need to point in the right direction.

My hashNode:

struct{
    hashNode(int k, std::string i) : key(k), item(i){};

    int key;
    std::string item;
}

      

My hash table:

class Hashtable
{
public:

    Hashtable(); //not sure how to build the constructor build an empty table.

    int hashFunction(int key);
    int find(int key);
    void insert(int key, std::string item);
    void remove(int key);

private:

    int tableSize = 10;
    std::shared_ptr<std::shared_ptr<hashNode>> hashTable;
    //std::vector<std::shared_ptr<hashNode>> hashTable;
};

      

I am stuck here as I don’t know if I am using the hash table correctly or not. Or if it's just a bad idea. Any advice will do.

+3


source to share


2 answers


Modify your attribute member hashNode

as a single pointer using std::unique_ptr

. Then, in the constructor of the HashTable, you can initialize it with std::make_unique

.

In HashTable.h

class Hashtable {
public:
   Hashtable(); 

   int hashFunction(int key);
   int find(int key);
   void insert(int key, std::string item);
   void remove(int key);

private:
   int tableSize = 10;
   std::unique_ptr<hashNode[]> hashTable;  // As stated in the comments.
};

      



In HashTable.cpp

Hashtable::Hashtable() {
   hashTable = std::make_unique<hashNode[10]>();
}

      

+1


source


HashTable example with containers

class Hashtable
{
public:
    Hashtable(): hashTable(10) // initial size set here
    {
        // does nothing
    }
    int hashFunction(int key);
    int find(int key);
    void insert(int key, std::string item); // this gets a bit more complicated
                                            // due to copying during rehash
    void remove(int key);

private:
    std::vector<std::vector<hashNode>> hashTable; // vector knows its size 
};

      



This makes rewriting a little more difficult as you now need to copy instead of moving the pointers, but at the top there are memory management issues or difficulty copying anything containing unique_ptr

. It wouldn't be unique if you copied it, would it?

0


source







All Articles