我想編輯我的哈希表來形成一個雙哈希類,但似乎無法得到它的權利。雙探針哈希表
我想知道是否有人有任何見解。我被告知,我所需要做的就是編輯findPos(),我現在必須使用新策略來提供新探測器。
**我做了一些研究,它說在雙重探測中,你會使用R-(x mod R),其中R>大小和小於表大小的素數。那麼我要做一個新的散列函數?
這裏是我的代碼:
template <typename HashedObj>
class HashTable
{
public:
explicit HashTable(int size = 101) : array(nextPrime(size))
{ makeEmpty(); }
bool contains(const HashedObj & x) const
{
return isActive(findPos(x));
}
void makeEmpty()
{
currentSize = 0;
for(auto & entry : array)
entry.info = EMPTY;
}
bool insert(const HashedObj & x)
{
// Insert x as active
int currentPos = findPos(x);
if(isActive(currentPos))
return false;
if(array[ currentPos ].info != DELETED)
++currentSize;
array[ currentPos ].element = x;
array[ currentPos ].info = ACTIVE;
// Rehash;
if(currentSize > array.size()/2)
rehash();
return true;
}
bool insert(HashedObj && x)
{
// Insert x as active
int currentPos = findPos(x);
if(isActive(currentPos))
return false;
if(array[ currentPos ].info != DELETED)
++currentSize;
array[ currentPos ] = std::move(x);
array[ currentPos ].info = ACTIVE;
// Rehash; see Section 5.5
if(currentSize > array.size()/2)
rehash();
return true;
}
bool remove(const HashedObj & x)
{
int currentPos = findPos(x);
if(!isActive(currentPos))
return false;
array[ currentPos ].info = DELETED;
return true;
}
enum EntryType { ACTIVE, EMPTY, DELETED };
private:
struct HashEntry
{
HashedObj element;
EntryType info;
HashEntry(const HashedObj & e = HashedObj{ }, EntryType i = EMPTY)
: element{ e }, info{ i } { }
HashEntry(HashedObj && e, EntryType i = EMPTY)
: element{ std::move(e) }, info{ i } { }
};
vector<HashEntry> array;
int currentSize;
bool isActive(int currentPos) const
{ return array[ currentPos ].info == ACTIVE; }
int findPos(const HashedObj & x) const
{
int offset = 1;
int currentPos = myhash(x);
while(array[ currentPos ].info != EMPTY &&
array[ currentPos ].element != x)
{
currentPos += offset; // Compute ith probe
offset += 2;
if(currentPos >= array.size())
currentPos -= array.size();
}
return currentPos;
}
void rehash()
{
vector<HashEntry> oldArray = array;
// Create new double-sized, empty table
array.resize(nextPrime(2 * oldArray.size()));
for(auto & entry : array)
entry.info = EMPTY;
// Copy table over
currentSize = 0;
for(auto & entry : oldArray)
if(entry.info == ACTIVE)
insert(std::move(entry.element));
}
size_t myhash(const HashedObj & x) const
{
static hash<HashedObj> hf;
return hf(x) % array.size();
}
};
只是爲了理解:你想說「雙重哈希」嗎?這是第一次碰撞通過調用第二個散列函數 – lrleon
@lrleon yes來解決。我是新來哈希但這就是我的意思 – HG319
@lrleon如果在findpos()我改變偏移+ = 2到 偏移=(偏移量+ currentPos)%array.size(); 會對雙重散列有意義嗎? – HG319