insert(Key,Value) 插入映射 可以直接通过 [] 插入或查询 虽然写的是泛型,但暂时不知道非整形的类型要怎么获取hash数,回头学下
#include<iostream>
#include<string>
using namespace std;
#ifndef UNORDEREDMAP
#define UNORDEREDMAP
template<typename Key, typename Value>
class hashNode
{
public:
Key key;
Value value;
hashNode* next;
hashNode(Key _key,Value _value):key(_key),value(_value),next(NULL){}
hashNode operator = (Value value)
{
this.value = value;
}
hashNode operator == (const hashNode& c)
{
return c.value == value;
}
hashNode operator == (Value vv)
{
return value == vv;
}
};
template<typename Key,typename Value>
class unordered_map
{
public:
int hash(Key key) const
{
return (key * 123 + 3) % this_size;
}
explicit unordered_map(int sz) :this_size(sz)
{
table = new hashNode<Key, Value> * [sz];
for (int i = 0;i < sz;i++) table[i] = NULL;
}
Value& operator [] (Key key)
{
int pos = hash(key);
hashNode<Key, Value>* now = table[pos];
while (now)
{
if (now->key == key) return now->value;
now = now->next;
}
throw "123";
}
void insert(Key key, Value value)
{
int pos = hash(key);
hashNode<Key, Value>* now = table[pos];
while (now)
{
if (now->key == key) { now->value = value; return; }
now = now->next;
}
hashNode<Key, Value>* tmp = new hashNode<Key, Value>(key, value);
tmp->next = table[pos];
table[pos] = tmp;
}
private:
int this_size;
hashNode<Key, Value>** table;
};
int main()
{
unordered_map<int, string>mp(10);
mp.insert(3, "旧的3");
mp.insert(5, "旧的5");
cout << mp[3] << ' ' << mp[5] << endl;
mp[3] = "新的3";
cout << mp[3] << ' ' << mp[5] << endl;
}
#endif UNORDEREDMAP
运行结果:
|