c – 使用智能指针制作哈希表?
发布时间:2020-12-16 07:20:50 所属栏目:百科 来源:网络整理
导读:我正在尝试使用智能指针制作哈希表,但我不确定我是否正确行事.我一直在尝试使用它们的两种组合,但我担心我不知道如何将表初始化为空?也许这是错误的问题,但我被困住了,我需要指出正确的方向. 我的hashNode: struct{ hashNode(int k,std::string i) : key(k
我正在尝试使用智能指针制作哈希表,但我不确定我是否正确行事.我一直在尝试使用它们的两种组合,但我担心我不知道如何将表初始化为空?也许这是错误的问题,但我被困住了,我需要指出正确的方向.
我的hashNode: 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]>(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |