以下是使用C++实现哈希表的代码。您能否帮助我理解
HashEntry **table
是什么?为什么它声明为双指针?它是一个数组,数组的每个值都是 HashEntry
吗?
HashEntry **table
是一个指向指针的指针,也可以称作二级指针。它用于创建一个动态的哈希表,其中每个条目(entry)都是一个指针。所以 `table` 本身是一个指向指针数组的指针。每个元素是一个 `HashEntry` 类型的指针,指向哈希表的一个具体的 entry。这样设计可以方便在哈希表的动态调整大小过程中,直接修改 table 数组的大小即可。 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;
}
};
const int TABLE_SIZE = 128;
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;
}
};
std::unordered_map
? - druckermanly