【发布时间】:2017-03-20 06:53:33
【问题描述】:
以下是使用C++实现的hashtable。你能帮我理解HashEntry **table是什么吗?为什么它被声明为双指针?是不是一个数组,数组的每个值都是HashEntry?
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吗? -
@user2899162 是的,
std::unordered_map实际上是哈希映射实现。 -
@Anni_housie HashEntry** 是一个动态二维数组
-
@Anni_housie 看看这个链接很有用:stackoverflow.com/questions/936687/…
标签: c++ hash hashmap hashtable