hash_map雜湊映照容器的實現
阿新 • • 發佈:2018-12-27
template<class KeyType,int MaxHash>
struct HashFunction
{
int operator()(const KeyType& key)
{
int h=key%MaxHash;
if (h<0) h+=MaxHash;
return h;
}
};
template<class KeyType,class ValueType,int KeyContain,int MaxHash,class HashFun=HashFunction<KeyType,MaxHash> >
class HashMap
{
public:
HashMap():hashfun(){Clear();}
ValueType& operator[](const KeyType& key)
{
int h=hashfun(key);
int pos=head[h];
for(;pos!=0;pos=next[pos])
{
if(keys[pos]==key)
return values[pos];
}
next[++top]=head[h];
head[h]=top;
keys[top]=key;
values[top]=ValueType();// 初始化 ++sz;
return values[top];
}
void Clear()
{
memset(head,0,sizeof(head));
memset(next,0,(top+1)*sizeof(int));
top=0;
sz=0;
}
unsigned int size() const {return sz;}
private:
unsigned int sz;
HashFun hashfun;
int head[MaxHash];
int next[KeyContain];
KeyType keys[KeyContain];
ValueType values[KeyContain];
int top;
};
struct HashFunction
{
int operator()(const KeyType& key)
{
int h=key%MaxHash;
if (h<0) h+=MaxHash;
return h;
}
};
template<class KeyType,class ValueType,int KeyContain,int MaxHash,class HashFun=HashFunction<KeyType,MaxHash> >
class
{
public:
HashMap():hashfun(){Clear();}
ValueType& operator[](const KeyType& key)
{
int h=hashfun(key);
int pos=head[h];
for(;pos!=0;pos=next[pos])
{
if(keys[pos]==key)
return values[pos];
}
next[++top]=head[h];
head[h]=top;
keys[top]=key;
values[top]=ValueType();//
return values[top];
}
void Clear()
{
memset(head,0,sizeof(head));
memset(next,0,(top+1)*sizeof(int));
top=0;
sz=0;
}
unsigned int size() const {return sz;}
private:
unsigned int sz;
HashFun hashfun;
int head[MaxHash];
int next[KeyContain];
KeyType keys[KeyContain];
ValueType values[KeyContain];
int
};