c++ 数组作为哈希表 键
时间: 2023-08-14 15:00:31 浏览: 326
在 C++ 中,数组可以用作哈希表的键,但需要一些额外的操作来处理哈希函数和冲突解决。
首先,你需要定义一个哈希函数,它将根据键的值计算出一个唯一的哈希码。这个哈希码将用于确定数组中的索引位置。
然后,你需要处理冲突。当两个不同的键计算出相同的哈希码时,就会发生冲突。一种常见的解决方法是使用开放地址法,其中冲突的元素被放置在数组中的下一个可用位置。
下面是一个简单的示例代码来演示使用数组作为哈希表键:
```cpp
#include <iostream>
const int TABLE_SIZE = 10;
// 哈希表项
struct HashEntry {
int key;
int value;
};
// 哈希表类
class HashTable {
private:
HashEntry *table[TABLE_SIZE];
public:
HashTable() {
for (int i = 0; i < TABLE_SIZE; i++) {
table[i] = nullptr;
}
}
// 哈希函数
int hashFunction(int key) {
return key % TABLE_SIZE;
}
// 插入键值对
void insert(int key, int value) {
int hash = hashFunction(key);
while (table[hash] != nullptr && table[hash]->key != key) {
hash = (hash + 1) % TABLE_SIZE;
}
if (table[hash] != nullptr) {
delete table[hash];
}
table[hash] = new HashEntry{key, value};
}
// 查找键对应的值
int get(int key) {
int hash = hashFunction(key);
while (table[hash] != nullptr && table[hash]->key != key) {
hash = (hash + 1) % TABLE_SIZE;
}
if (table[hash] != nullptr) {
return table[hash]->value;
}
return -1; // 键不存在
}
// 删除键值对
void remove(int key) {
int hash = hashFunction(key);
while (table[hash] != nullptr && table[hash]->key != key) {
hash = (hash + 1) % TABLE_SIZE;
}
if (table[hash] != nullptr) {
delete table[hash];
table[hash] = nullptr;
}
}
~HashTable() {
for (int i = 0; i < TABLE_SIZE; i++) {
if (table[i] != nullptr) {
delete table[i];
}
}
}
};
int main() {
HashTable hashTable;
// 插入键值对
hashTable.insert(1, 10);
hashTable.insert(2, 20);
// 查找键对应的值
std::cout << hashTable.get(1) << std::endl; // 输出: 10
std::cout << hashTable.get(2) << std::endl; // 输出: 20
// 删除键值对
hashTable.remove(1);
std::cout << hashTable.get(1) << std::endl; // 输出: -1 (键不存在)
return 0;
}
```
这个示例代码演示了如何使用数组实现一个简单的哈希表。你可以根据需要进行扩展和修改,以适应你的具体应用场景。
阅读全文