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