c++ - 为什么我需要一个对象数组的双指针? C++ 中的 HashMap 示例

标签 c++ pointers double-pointer

我正在练习一些 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/

相关文章:

c++ - 内存屏障会驯服微软的优化器吗?

c++ - 编译器优化破坏代码

c - 我应该 free() 用于存储 realloc() 结果的临时指针吗?

c - 在C语言中,如何通过双指针访问数组中的元素

c++ - 运行 .exe 文件时出现 std::logic 错误

c++ - gcc 未给出 Clang 错误 "attempted to construct a reference element in a tuple with an rvalue"

c - 使用指针改变矩阵

c++ - 指针类辅助

c - C语言中argv函数和字符串作为地址

c - 打印双指针字符数组时出现运行时错误