标签:
看了算法导论的影印版的哈希表时,开始还不太明白, 想了下后觉得似乎哈希表就是数组和链表的组合, 于是根据这个思路实现了一个最简易的哈希表。
这个其实我还是不太满意, 可能在以后会更新, 因为我觉得不满足 DRY 原则。
class HashTable
{
private:
const size_t initSize = 13;
const int32_t hashNum = 13;
vector<list<int32_t>> hashTable;
int32_t Hash (const int32_t& key) const
{
return (key % hashNum);
}
list<int32_t>::const_iterator
GetTargetIter (const int32_t& value) const
{
auto key = Hash (value);
return find (hashTable[key].cbegin (),
hashTable[key].cend (),
value);
}
public:
explicit HashTable ()
{
hashTable.resize (initSize);
}
decltype(hashTable) GetHashTable () const
{
return hashTable;
}
HashTable& operator=(const HashTable& otherTable)
{
hashTable = otherTable.GetHashTable ();
return *this;
}
void Insert (const int32_t& value)
{
if (GetTargetIter (value) ==
hashTable[Hash (value)].cend ()) {
hashTable[Hash (value)].push_back (value);
}
else {
cerr << "Insert failed: The value already exists.\n";
}
}
void Delete (const int32_t& value)
{
auto targetIter = GetTargetIter (value);
auto key = Hash (value);
if (targetIter == hashTable[key].cend ()) {
cout << "Cannot find " << value << " !\n";
}
else {
hashTable[key].erase (targetIter);
cout << "The " << value << " has been deleted!\n";
}
}
void Search (const int32_t& value) const
{
if (GetTargetIter (value) ==
hashTable[Hash (value)].cend ()) {
cout << "Cannot find "<< value << " !\n";
}
else {
cout << value << " is exist.\n";
}
}
void Show () const
{
cout << "The values in the hash table are:\n";
for_each (hashTable.cbegin (), hashTable.cend (),
[] (const list<int32_t>& l)
{
if (!l.empty ()) {
for (const auto& val : l) {
cout << val << " ";
}
cout << endl;
}
});
}
};
标签:
原文地址:http://www.cnblogs.com/wuOverflow/p/4300363.html