哈希映射使用 nullptr c++ 初始化节点的动态数组

Hashmap initializing dynamic array of nodes with nullptr c++

本文关键字:节点 动态 数组 初始化 c++ 映射 nullptr 哈希      更新时间:2023-10-16

我在使用 nullptr 正确初始化节点的动态数组时遇到问题。

HashMap::HashMap(int size)
{
this->sizeOfArray = size;
this->hashArray = new Node*[this->sizeOfArray];
for (int i = 0; i < this->sizeOfArray; i++)
{
hashArray[i] = nullptr;
}
}

这就是我的"哈希数组"在标题中的样子。

Node **hashArray;

forloop 完成了所有 500 个循环,但是当我查看数组中的数据时,我只能看到第一个元素,然后才能得到"无法读取内存"。

这是我的意思的图片 https://ibb.co/d0GLw9

这是节点的样子

Node()
{
value = 0;
}
Node(std::string input)
{
key = input;
value = 1;
next = nullptr;
}
Node(std::string input, int count)
{
key = input;
this->value = count;
next = nullptr;
}
Node(std::string input, int count, Node *next)
{
key = input;
this->value = count;
this->next = next;
}
Node *next;
std::string key;    
unsigned int value; 

我怀疑这个问题导致我以后无法向哈希数组添加任何新节点。

所有 500 个Node指针都是NULL的,但是hashArray的类型是Node **,这就是为什么调试器只显示一个元素,就好像它是指向一个Node指针的指针一样。换句话说,由于数组是动态的,调试器不知道要显示多少个元素。

您遇到的错误是关于查看指针为NULL的第一个Node的内容,这自然是无法读取的。