example of a hash - superfulous code
I found this snippet here as an example of the simplest kind of hash. It kind of makes since..basically use the modulus operator to reduce a data set from DATA_SIZE(im开发者_如何学Pythonplied) to TABLE_SIZE(defined).
However, if a collision occurs, i.e. the array element is already taken, it moves to
hash = (hash + 1) % TABLE_SIZE
But if you already did a modulus using TABLE SIZE this line will always produce (hash+1) b.c. x % y always equals x when x < y. Question: Is this a bug...I mean it should work but the % TABLE_SIZE is extra right? It does nothing in the code below.
const int TABLE_SIZE = 128;
class HashEntry
{
private:
int key;
int value;
public:
HashEntry(int key, int value)
{
this->key = key;
this->value = value;
}
int getKey()
{
return key;
}
int getValue()
{
return value;
}
};
class HashMap
{
private:
HashEntry **table;
public:
HashMap()
{
table = new HashEntry*[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++) table[i] = NULL;
}
int get(int key)
{
int hash = (key % TABLE_SIZE);
while (table[hash] != NULL && table[hash]->getKey() != key) hash = (hash + 1) % TABLE_SIZE;
if (table[hash] == NULL)return -1;
else return table[hash]->getValue();
}
void put(int key, int value)
{
int hash = (key % TABLE_SIZE);
while (table[hash] != NULL && table[hash]->getKey() != key) hash = (hash + 1) % TABLE_SIZE;
if (table[hash] != NULL) delete table[hash];
table[hash] = new HashEntry(key, value);
}
~HashMap()
{
for (int i = 0; i < TABLE_SIZE; i++)
if (table[i] != NULL) delete table[i];
delete[] table;
}
};
That modulus is there in case of overflow.
suppose hash == TABLE_SIZE - 1
. Then hash + 1 == TABLE_SIZE
, whereas hash+1 % TABLE_SIZE == 0
.
精彩评论