c++ - 使用智能指针制作哈希表?

标签 c++ vector hashtable smart-pointers

我正在尝试使用智能指针制作哈希表,但我不确定我做的是否正确。我一直在尝试使用它们的两种组合,但恐怕我不知道如何将表格初始化为空?也许这是错误的措辞,但我被卡住了,我需要指出正确的方向。

我的哈希节点:

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

    int key;
    std::string item;
}

我的哈希表:

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]>();
}

关于c++ - 使用智能指针制作哈希表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43173579/

相关文章:

c++ - 该递归函数如何工作?

c++ - pthread_mutex_t 作为类成员导致死锁

c++ - 用迭代器修改容器的内容

c++ - C++ 程序中的 TCHAR 和未解析的外部符号 (LNK2019) 错误?

c++ - 是否实例化了所有有效模板?

c++ - 退出函数后 vector 大小变为 0

c++ - 让基于范围的 for 循环从 vector 中的点开始

powershell - 在 powershell 中对哈希表中的多个值进行排序

c - 几次重新分配后出现段错误 |结构数组

c++ - 枚举作为 C++ 中函数的返回类型