c++ - "Error reading character of string"为散列动态增长数组的问题 (C++)

标签 c++ pointers hash

每当代码尝试在增长函数中将旧数组中的值插入到新数组中时,我都会收到错误“读取字符串字符时出错”。 当阵列达到某个负载因子时,我试图增加阵列。我试图弄清楚问题是什么,但我不知道它是什么。我已经为 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。从 capacitynewCapacity 的"new"元素未初始化。

将初始化循环更改为

for (int i = 0; i < newCapacity; i++)

关于c++ - "Error reading character of string"为散列动态增长数组的问题 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49825850/

相关文章:

c++ - 整数对的哈希算法

C++虚拟继承和类型转换/复制构造函数混淆

c++ - 为什么指向 vector 中变量的指针保持有效?

c++ - 如何实时捕捉摄像头的视频?

c++ - 我不能在 C++ 函数中使用 new 来构建

c - openmp 在指针数组和指向数组的指针之间的性能差异有什么问题?

arrays - 对作为哈希值的数组进行排序

hash - CouchDB 文档 ID 是如何计算的?

c++ - 如何在不使用任何数据库的情况下制作动态注册表单?

c++ - 显示像素值已更改的图像 openCV