【问题标题】:Implementing resize of a hash table in C++在 C++ 中实现散列表的大小调整
【发布时间】:2020-04-23 01:36:33
【问题描述】:

我在 C++ 中实现调整大小或扩展容量功能时遇到问题。这是我的 resize(expandCapacity) 函数:

    template <typename K, typename V> void HashTable<K, V>::expandCapacity() {
    LinearDictionary<K,V>* temp = this->hashTable;
    this->capacity *= 2;
    this->hashTable = new LinearDictionary<K,V>[this->capacity];
    for(int i = 0; i < capacity; i++){
      vector<pair<K,V>> items = temp[i].getItems();
      for(int j = 0;j < temp[i].getSize(); i++){
        K key = items[j].first;
        V value = items[j].second;
        int bucket = hash(key, capacity);
        this->hashTable[bucket].insert(key, value);
      }
    }
    delete temp;
}

这是我的插入函数:

    template <typename K, typename V> void HashTable<K, V>::insert(K key, V value) {
    int bucket = hash(key, capacity);
    if(this->hashTable[bucket].contains(key)){
        throw runtime_error("This key already exists");
      }
    this->hashTable[bucket].insert(key,value);
    size+=1;
    float loadFactor = (float)(size)/(float)(capacity);
    if(loadFactor >= maxLoadFactor){
      this->expandCapacity();
    }
   }

模板 K 代表键,V 代表值。哈希表被实现为一个指向线性字典数组的指针(我自己实现的一个类,它本质上是一个键值对列表,对字典有一些额外的有用功能)。但这似乎并没有扩大容量。相反,我不断收到错误“密钥已存在” - 这是我的教授实施的运行时错误。

【问题讨论】:

  • 顺便说一句,实现扩展操作的一个相对简单的方法是首先实现一个swap_contents(HashTable & rhs)方法,它只是交换(this)和(rhs)的成员变量。一旦你实现了它,你可以简单地通过声明一个具有更大数组大小的临时第二个 HashTable 对象来实现 expandCapacity(),调用 temp=*this;然后调用 swap_contents(temp)

标签: c++ hash hashmap hashtable


【解决方案1】:

您的i 循环进行了太多迭代。它基于新容量循环,当它正在访问的temp数据只有旧容量元素时。

【讨论】:

    猜你喜欢
    • 2013-06-20
    • 2020-12-09
    • 1970-01-01
    • 2016-06-18
    • 2015-09-14
    • 1970-01-01
    • 2016-03-07
    • 2020-03-06
    • 2016-08-21
    相关资源
    最近更新 更多