hash_map錛岄【鍚嶆濅箟錛屽氨鏄埄鐢?/span>hash_set瀛樺偍緇撴瀯鐨勫啓map鏄犵収瀹瑰櫒錛屾櫘閫氱殑map鐢ㄧ殑鏄孩榛戞爲瀛樺偍緇撴瀯鍐欑殑銆傚厓绱犵殑媯绱㈡椂闂村姣旓紝hash_set榪戜技涓?/span>O(1)錛岀孩榛戞爲涓?/span>O(logn)銆?/span>Hash_map鐨勭┖闂村紑閿瑕佹瘮map 鐨勭┖闂村紑閿澶э紝灝ゅ叾鏄垜鐢ㄦ暟緇勬ā鎷熸寚閽堝啓鐨?/span>hash_map銆?/span>
鎵浠ワ紝濡傛灉鏈夊繀瑕侀噰鍙栨槧灝勭粨鏋勭殑鏃跺欙紝鑳界敤hash_map灝卞埆鐢?/span>map銆?/span>
闇瑕佹敞鎰忕殑鏄紝hash_map閬嶅巻鍑烘潵鐨勫厓绱犱笉鏄湁搴忕殑銆?/span>
Hash_map鍜屾櫘閫?/span>hash_set鐩告瘮鐨勮瘽錛?/span>hash_map姣?/span>hash_set澶氫簡涓寮?/span>value琛紝涔熷氨鏄槧灝勮〃銆?/span>
涓嬮潰鏄?/span>hash_map鐨勬ā鏉匡紝鍜?/span>hash_set鐨勬ā鏉垮樊涓嶅銆?br />
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();//鍒濆鍖?/span>
++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;
};

]]>