【问题标题】:Hash Table Separate Chaining with Vectors哈希表与向量分离链接
【发布时间】:2021-06-25 03:55:13
【问题描述】:

我目前正在尝试使用向量制作哈希表,但不确定如何调用某些值。我们使用类型 K 和 V,我猜类型 V 是值,因为类型 K 在大多数情况下代表键,但我迷失了如何执行以下一些功能:

#include <iostream>
#include <vector>
#include <list>
#include <stdexcept>

// Custom project includes
#include "Hash.h"

// Namespaces to include
using std::vector;
using std::list;
using std::pair;

//
// Separate chaining based hash table - inherits from Hash
//
template<typename K, typename V>
class ChainingHash : public Hash<K,V> {

    int table_size;

private:
    vector<list<V>> table;          // Vector of Linked lists

public:

    ChainingHash(int n = 11) : table(n){

        //this -> table_size = n;

        //table = new vector<list<K,V>>(n);

    }

    ~ChainingHash() {
        //this->clear();
    }

    bool empty() {
    
        if (!table.empty()) {
            return false;
        }
    
        return true;

    }

    int size() {

        return table.size();

    }

    //Returns the value with key k
    V& at(const K& key) {
        throw std::out_of_range("Key not in hash");
    }

    //Returns the value with key k
    V& operator[](const K& key) {
    } 


    //Returns the number of elements with key k
    int count(const K& key) {

        for (int i = 0; i < table.size(); i++) {
        
        }

    }

    //Adds element with key, true if successful
    void emplace(K key, V value) {
    }

    //Adds pair to hash, true if successful
    void insert(const std::pair<K, V>& pair) {
    }

    //Removes all any (if any) entries with key k
    void erase(const K& key) {
    }

    //Empties the hash
    void clear() {

        for (int i = 0; i < table.size(); i++) {
        
    }

}

我不需要所有功能的帮助,但我想了解使用键和值来查找它们属于哪个存储桶的要点。我大多只是不确定值(数字)是什么也就是说,我们应该给与其余代码相关的标签。另外,如果您到目前为止在我的代码中发现任何错误,请随时提及!非常感谢!

我也在为函数 int count 苦苦挣扎,只是当你找到具有相同键的存储桶时,你将如何搜索链表,我不确定它是否只是 item->next 或者如果它被称为别的东西。

【问题讨论】:

    标签: c++ function vector hashtable chaining


    【解决方案1】:

    您需要使用哈希函数(我猜它由代码中的Hash.h 提供)对密钥进行哈希处理,然后找到 bucket(在这种情况下为向量的索引)插入 key in。如果多个键散列到同一个桶中,您只需将键添加到列表中即可。使用list::insert() 插入(reference)。

    要检索与键关联的值,您实际上需要将&lt;Key,Value&gt;pair (reference) 存储在列表中,以便迭代碰撞并添加的键列表到同一个bucket,可以取到value。

    对于链表的搜索,只需以常规的for(a:x)方式遍历即可

    list = table[idx]; //idx found after hashing the key
    int count = 0;
    for(const auto& elem: list) {
        if(elem.first == key) {
           count++;
        }
    }
    return count;
    

    【讨论】:

      猜你喜欢
      • 2020-09-03
      • 1970-01-01
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      • 2012-05-06
      • 1970-01-01
      • 2012-04-23
      • 2021-11-26
      相关资源
      最近更新 更多