#include <iostream>
#include <string>
#include <queue>
using namespace std;
class HashFunc{
public:
int operator()(const int key){
return 3*key + 1;
}
};
template <class Key, class Value>
class HashNode{
public:
Key key;
Value value;
HashNode* next;
HashNode(Key _key, Value _value) : key(_key), value(_value), next(nullptr){}
~HashNode(){}
};
template <class Key, class Value, class HashFunc>
class HashMap{
public:
Value valuenull;
HashMap(int size);
~HashMap();
bool insert(Key key, Value value);
bool del(Key &key);
Value &find(Key &key);
Value &operator[](Key &key);
void print();
private:
int size;
HashFunc hash;
HashNode<Key, Value> **table;
};
template <class Key, class Value, class HashFunc>
HashMap<Key, Value, HashFunc>::HashMap(int _size): size(_size), hash(){
table = new HashNode<Key, Value>*[_size];
for(int i=0; i<_size; ++i){
table[i] = nullptr;
}
}
template <class Key, class Value, class HashFunc>
HashMap<Key, Value, HashFunc>::~HashMap(){
for(int i=0; i<size; ++i){
HashNode<Key, Value> *cur = table[i];
while(cur){
HashNode<Key, Value> *tmp = cur;
cur = cur->next;
delete tmp;
tmp = nullptr;
}
}
delete table;
}
template <class Key, class Value, class HashFunc>
bool HashMap<Key, Value, HashFunc>::insert(Key key, Value value){
int index = hash(key) % size;
HashNode<Key, Value> *hnode = new HashNode<Key, Value>(key, value);
hnode->next = table[index];
table[index] = hnode;
return true;
}
template <class Key, class Value, class HashFunc>
bool HashMap<Key, Value, HashFunc>::del(Key &key){
int index = hash(key) % size;
HashNode<Key, Value> *cur = table[index];
if(cur==nullptr) return false;
if(cur->key==key){
table[index] = cur->next;
delete cur;
cur = nullptr;
return true;
}
HashNode<Key, Value> *pre = cur;
cur = cur->next;
while(cur){
if(cur->key==key){
pre->next = cur->next;
delete cur;
cur = nullptr;
return true;
}else{
cur = cur->next;
pre = pre->next;
}
}
return false;
}
template <class Key, class Value, class HashFunc>
Value &HashMap<Key, Value, HashFunc>::find(Key &key){
int index = hash(key) % size;
if(table[index]==nullptr) return valuenull;
HashNode<Key, Value> *cur = +[index];
while(cur){
if(cur->key==key) return cur->value;
else cur = cur->next;
}
return valuenull;
}
template <class Key, class Value, class HashFunc>
Value &HashMap<Key, Value, HashFunc>::operator[](Key &key){
return find(key);
}
template <class Key, class Value, class HashFunc>
void HashMap<Key, Value, HashFunc>::print(){
for(int i=0; i<size; ++i){
HashNode<Key, Value> *cur = table[i];
while(cur){
cout<<cur->value<<" ";
cur = cur->next;
}
}
}
int main()
{
HashMap<int, int, HashFunc> hashmap(10);
hashmap.insert(1, 1);
hashmap.insert(11, 5);
hashmap.print();
cout << "----------" << endl;
hashmap.insert(2, 8);
int num = 1;
hashmap.del(num);//删除键值为1的
hashmap.print();
system("pause");
return 0;
}
c++实现简单的unordered_map
最新推荐文章于 2024-05-28 22:06:57 发布