我正在练习一些 C++,我很困惑为什么我需要一个对象数组(例如节点结构)的双指针。这是一个简单的代码片段来解释我的情况:
struct HashNode{
HashNode* next;
int data;
int key;
int hashCode;
HashNode::HashNode(
HashNode* next,
const int& data,
const int& key,
const int& hashCode
) : next(next), data(data), key(key), hashCode(hashCode)
{}
};
class HashMap{
public:
HashMap();
HashMap(int tableSize);
~HashMap();
private:
//Here is the double pointer
HashNode** table;
};
HashMap::HashMap(){
//Here is the array initialization
table = new HashNode*[100];
}
我已经删除了该问题不需要的代码。
如果我这样删除双指针:
HashNode* table;
和
table = new HashNode[100];
我收到以下错误。
hashmap.cpp: In method `HashMap::HashMap()':
hashmap.cpp:87: no matching function for call to `HashNode::HashNode ()'
hashmap.cpp:61: candidates are: HashNode::HashNode(const HashNode &)
hashmap.cpp:58: HashNode::HashNode(HashNode *, const int &, cons
t int &, const int &)
这表明 HashNode 试图运行一个构造函数。
如果我仅将数组的初始化更改为 table = new HashNode*[100];
,同时保留 HashNode* table;
,则会出现以下错误。
hashmap.cpp: In method `HashMap::HashMap()':
hashmap.cpp:87: assignment to `HashNode *' from `HashNode **'
我的假设是,当我创建一个对象数组时,我需要对象的生命周期也与程序的持续时间相同。这要求我对对象和数组使用指针。因此,我需要数组的双指针,因为它指向指针,我需要对象的指针。
但是,我仍然不确定,我在网上找不到任何好的解释。有人可以解释一下这种情况吗?
最佳答案
此实现使用 separate chaining with linked lists用于管理哈希冲突。因此,table
是指向HashNode
的指针数组,这意味着它需要两个星号:
- 一个星号来自数组元素的类型,即
HashNode*
- 另一个星号来自制作一个
HashNode*
数组
这也是为什么在 new
表达式中有一个星号:
table = new HashNode*[100];
// ^
关于c++ - 为什么我需要一个对象数组的双指针? C++ 中的 HashMap 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45468789/