template<typename T,typename V>
struct LNode {
T key;
V value;
LNode * next;
LNode(const T m_key, const V m_value) :key(m_key), value(m_value), next(nullptr) {};
};
template<typename T, typename V>
class hash_map
{
public:
void insert(T key, V value) {
long hashValue = std::hash<T>()(key);//获取哈希值
int hashKey = hashValue % HASH_NUM;//获取哈希索引
LNode<T, V>* pNode = new LNode<T, V>(key, key);//构造插入的节点 K-V
LNode<T, V>* LocalHash = HashTable[hashKey];//查看哈希表位置
if (LocalHash == NULL) {//位置为空 直接插入
HashTable[hashKey] = pNode;
}
else {//不为空 开链法
LNode<T, V>* InsetHashLocal = nullptr;//记录最后一个链表的位置
while (LocalHash != nullptr) {
InsetHashLocal = LocalHash;
LocalHash = LocalHash->next;//寻找链表最后位置
}
InsetHashLocal->next = pNode;//插入构造的节点
LocalHash = pNode;//改变链表指针
}
}
pair<T,V>find(T key) {
long hashValue = std::hash<T>()(key);//获取哈希值
int hashKey = hashValue % HASH_NUM;//获取哈希索引
LNode<T, V>* node = HashTable[hashKey];//查看哈希表位置
while (node != nullptr)//顺着链表寻找
{
if (node->key == key) {//找到对应的key
cout << key << "," << node->value << endl;
return { node->key,node->value };
}
node = node->next;
}
cout << "not find K-V data" << endl;
return {-1,-1};
}
void remove(T key) {
long hashValue = std::hash<T>()(key);//获取哈希值
int hashKey = hashValue % HASH_NUM;//获取哈希索引
LNode<T, V>* node = HashTable[hashKey];
while (node != nullptr) {
LNode<T, V>* temp = nullptr;
if (node->key != key) {
temp = node;
node = node->next;
}
else{
if (node->next) {
temp->next = node->next;
}
else {
temp->next = nullptr
}
break;
}
}
}
void print() {
for (int i = 0; i < HASH_NUM; i++) {
LNode<T, V>* node = HashTable[HASH_NUM];
cout << i << ":";
while (node != nullptr) {
cout << "(" << node->key << "," << node->value << ")";
node->next;
}
cout << endl;
}
}
private:
LNode<T, V>* HashTable[HASH_NUM];
};
基于低层哈希表的key-value容器(map容器)
最新推荐文章于 2023-01-04 17:48:54 发布