如何解决散列表与向量分开链接
我目前正在尝试使用向量创建哈希表,但不确定如何调用某些值。我们正在使用类型 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 或它被称为别的东西。
解决方法
您需要使用哈希函数(我猜是由代码中的 Hash.h
提供)对密钥进行哈希处理,然后找到要插入的 bucket(在本例中为向量索引) key in。如果多个键散列到同一个桶中,您只需将键添加到列表中。使用 list::insert()
插入(reference)。
要检索与键关联的值,您实际上需要在列表中存储 pair
的 <Key,Value>
(reference),以便在迭代列表时碰撞并添加到同一个存储桶中的键,可以检索该值。
要搜索链表,只需以常规的 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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。