"读取字符串"针对哈希(C ++)动态增长数组的问题

时间:2018-04-13 22:21:48

标签: c++ pointers hash

每当代码尝试将旧数组中的值插入到grow函数中的新数组中时,我会收到错误"读取字符串"时出错。 我正在尝试在达到某个负载因子时增大阵列。我试图弄清问题是什么,但我不知道它是什么。我已经为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;
    }
}

1 个答案:

答案 0 :(得分:2)

grow中,在为新表分配内存后,您只需将原始capacity元素设置为NULL。 &#34;新&#34;从capacitynewCapacity的元素未初始化。

将初始化循环更改为

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