每当代码尝试在增长函数中将旧数组中的值插入到新数组中时,我都会收到错误“读取字符串字符时出错”。 当阵列达到某个负载因子时,我试图增加阵列。我试图弄清楚问题是什么,但我不知道它是什么。我已经为 grow、insert 和 choosePrime 函数提供了代码。主要问题出在增长功能上,但我不知道这些其他功能是否影响了它。感谢您的帮助!
void grow() {
int newCapacity = choosePrime();
Slot **tmp = table;
table = new Slot*[newCapacity];
for (int i = 0; i < capacity; i++) {
table[i] = NULL;
}
for (int i = 0; i < capacity; i++) {
if (tmp[i] != NULL) {
Insert(tmp[i]->key, tmp[i]->value);
delete tmp[i];
}
}
capacity = newCapacity;
delete[] tmp;
}
/* Chooses Prime Number */
int choosePrime() {
int n = capacity * 2;
bool foundMultiple = false;
do {
n++;
for (int i = 1; i < n; i++) {
if (n % i == 0) {
foundMultiple = true;
}
}
} while(foundMultiple == false);
return n;
}
bool Insert(string key, int value)
{
if (float(size) / float(capacity) >= 0.5) {
grow();
}
int h = hash(key);
if (table[h] == NULL)
{
size++;
table[h] = new Slot;
table[h]->key = key;
table[h]->value = value;
table[h]->nextSlot = nullptr;
return true;
}
else if (table[h]->key == key)
{
return false;
}
else
{
int p = probe(key, 1);
for (int i = 1; h != p; p = probe(key, ++i))
{
if (table[p] == NULL)
{
size++;
table[p] = new Slot;
table[p]->key = key;
table[p]->value = value;
return true;
}
else if (table[p]->key == key)
{
return false;
}
}
return false;
}
}
最佳答案
在grow
中,为新表分配内存后,只需将原始capacity
元素设置为NULL
。从 capacity
到 newCapacity
的"new"元素未初始化。
将初始化循环更改为
for (int i = 0; i < newCapacity; i++)
关于c++ - "Error reading character of string"为散列动态增长数组的问题 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49825850/