#include <iostream>
#include <vector>
using namespace std;
enum Status
{
EXIST,
EMPTY,
DEL
};
template<class k, class v>
struct HashData
{
pair<k, v> _data;
Status _status = EMPTY;
};
template<class k, class v>
class HashTable
{
public:
bool insert(const pair<k, v>& data);
HashData<k,v>* find(const k& key);
bool erase(const k& key);
private:
vector<HashData<k,v> > _table;
int _count=0;
};
template<class k, class v>
bool HashTable<k,v>::insert(const pair<k,v>& data)
{
HashData<k, v> * res = find(data.first);
if(res)
{
return false;
}
if(_table.size() == 0 || _count * 10 / _table.size() >= 7)
{
int newSize = _table.size() == 0 ? 10 : 2 * _table.size();
HashTable<k, v> newHT;
newHT._table.resize(newSize);
for(int i=0; i<_table.size(); i++)
{
if(_table[i]._status == EXIST)
{
newHT.insert(_table[i]._data);
}
}
_table.swap(newHT._table);
}
int start = data.first % _table.size();
int index = start;
int i = 1;
while(_table[index]._status != EMPTY) // 被占用
{
// index = start + i;
index = start + i*i;
i++;
index %= _table.size();
}
_table[index]._data = data;
_table[index]._status = EXIST;
++_count;
return true;
}
template<class k, class v>
HashData<k,v>* HashTable<k, v>::find(const k& key)
{
if(_table.size() == 0 || _count == 0)
{
return nullptr;
}
int index = key % _table.size();
while(_table[index]._status != EMPTY)
{
if(_table[index]._status == EXIST && _table[index]._data.first == key)
{
return &_table[index];
}
++index;
index %= _table.size();
}
return nullptr;
}
template<class k, class v>
bool HashTable<k, v>::erase(const k& key)
{
HashData<k, v> * res = find(key);
if(res == nullptr)
{
return false;
}else
{
res->_status = DEL;
--_count;
return true;
}
}
int main()
{
HashTable<int, int> ht;
int a[] = {2, 14, 5, 6, 4};
for(auto e:a)
{
ht.insert(make_pair(e, e));
}
cout << ht.find(14) << endl;
ht.erase(14);
cout << ht.find(14) << endl;
}
参考:
c++哈希