# pragma>退出,
删除
空,
};
template<类K类V>
struct KeyValueNode//KV键值对
{
K _key;
V _value;
KeyValueNode (const K&关键=K (), const V&值=https://www.yisu.com/zixun/V ())
: _key(关键)
, _value(值)
{}
};
静态size_t BKDRHash (const char * str)//哈希算法
{
unsigned int种子=131;//31 131 1313 13131 131313
unsigned int散列=0;
, (* str)
{
散列=散列*种子+ (* str + +);}
返回(散列,0 x7fffffff);
}
template<类K>//仿函数
struct HashFuner
{
size_t运营商()(const K&键)
{
回车键;
}
};
template<在//特化
struct HashFuner
{
size_t运营商()(const string&键)
{
返回BKDRHash (key.c_str ());}
};
template<类K、V类,类HashFun=HashFuner
{
typedef KeyValueNode
散列表()
: _tables (NULL)
, _capacity (0)
, _size (0)
, _status (0)
{}
散列表(int容量)
: _tables(新KVNode[能力])
, _capacity(能力)
, _size (0)
, _status(新状态[能力])
{
(int i=0;我& lt;能力;+ + i)
{
_status[我]=空;
}
}
散列表(const HashTable
: _tables (NULL)
, _status (NULL)
{
HashTable
(int i=0;我& lt;_capacity;+ + i)
{
_tables[我]。_key=ht._tables[我]._key;
_tables[我]。_value=https://www.yisu.com/zixun/ht._tables[我]._value;
_size=ht._size;
_status[我]=ht._status[我];
}
这→交换(newtable);}
HashTable
{
这→交换(ht);
返回*;
}
~散列表()
{
如果(_tables)
{
删除[]_tables;
删除[]_status;
}
}公共:
bool插入(const K&键,const V&值)
{
如果(_capacity==_size)
{
HashTable
(size_t我=0;我& lt;_capacity;+ + i)
{
如果(_status[我]==出口)
{
size_t指数=HashFunc0 (_tables[我]._key);
(newtables。_status[我]==出口)
{
指数=HashFunc2(指数,我+ +);}
newtables。_tables(指数)=KVNode (_tables[我]._key _tables[我]._value);
newtables。_status(指数)=出口;
+ + _size;
}
}
这→交换(newtables);}
size_t指数=HashFunc0(关键);
int i=1;
, (_status(指数)==出口)
{
指数=HashFunc2(指数,我+ +);}
_tables(指数)=KVNode(键,值);
_status(指数)=出口;
_size + +;
返回true;
}
bool Remove (const K&键)
{
size_t指数=HashFunc0(关键);
int i=1;
, (_tables(指数)!=空)
{
如果_tables(指数)。_key==键)
{
如果(_status(指数)==出口)
{
——_size;
_status(指数)=删除;
返回true;
}
其他{
返回false;
}
}
指数=HashFunc2(指数,我+ +);}
返回false;
}
KVNode *找到(const K&键)
{
size_t指数=HashFunc0(关键);
int i=0;
, (_status(指数)!=空)
{
如果(关键==_tables[指数]._key)
{
如果(_status(指数)==出口)
返回,_tables(指数);其他
返回NULL;
}
指数=HashFunc2(指数,我+ +);}
返回NULL;
}
size_t HashFunc0 (const K&键)
{
返回HashFun()(关键)% _capacity;
}
size_t HashFunc2 (size_t prevValue, int i)
{
返回(prevValue + 2 * i - 1) % _capacity;
}
空白交换(HashTable
{
交换(_tables ht._tables);
交换(_status ht._status);
交换(_size ht._size);
交换(_capacity ht._capacity);}
保护:
KVNode * _tables;
int _capacity;
int _size;
状态* _status;
};