使用智能指针创建散列 table?

Make a hash table using smart pointers?

我正在尝试通过使用智能指针来生成散列table,但我不确定我做的是否正确。我一直在尝试玩它们的两种组合,但恐怕我不知道如何将 table 初始化为空?也许这是错误的措辞,但我被卡住了,我需要指出正确的方向。

我的哈希节点:

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

    int key;
    std::string item;
}

我的哈希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;
};

我被困在这里,因为我不知道我是否正确地实现了我的 hashTable。或者,如果这只是一个坏主意。任何建议都可以。

使用 std::unique_ptr 将您的 hashNode 属性成员更改为单个指针。然后,在 HashTable 的构造函数中,您可以使用 std::make_unique.

对其进行初始化

在你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.
};

在你的HashTable.cpp

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

带容器的哈希表示例

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

这使重新散列稍微复杂化,因为现在您必须复制而不是四处移动指针,但从好的方面来看,复制包含 unique_ptr 的内容时内存管理问题或困难为零。如果您复制它,它就不是独一无二的,对吗?