哈希表数据结构的代码
时间: 2024-05-24 21:08:06 浏览: 15
哈希表(Hash Table)是一种根据关键字直接访问内存存储位置的数据结构,它通常用于快速检索和查找数据。哈希表的核心思想是通过将关键字映射到一个大的数组中,来实现快速的查找和插入操作。下面是一个哈希表的示例代码:
```
#include <iostream>
#include <vector>
using namespace std;
class HashTable {
private:
vector<int> table; // 存储哈希表的数组
int size; // 哈希表大小
public:
HashTable(int tableSize) {
size = tableSize;
table.resize(size, -1); // 初始化数组,-1表示该位置没有元素
}
// 哈希函数,将关键字映射到数组中
int hashFunc(int key) {
return key % size;
}
// 插入元素
void insert(int key) {
int index = hashFunc(key);
while (table[index] != -1) { // 若该位置已经有元素,则向后寻找下一个位置
index = (index + 1) % size;
}
table[index] = key; // 将元素插入到该位置
}
// 查找元素
bool search(int key) {
int index = hashFunc(key);
while (table[index] != -1) { // 若该位置有元素,则向后寻找下一个位置
if (table[index] == key) {
return true; // 找到元素,返回true
}
index = (index + 1) % size;
}
return false; // 没有找到元素,返回false
}
// 删除元素
void remove(int key) {
int index = hashFunc(key);
while (table[index] != -1) { // 若该位置有元素,则向后寻找下一个位置
if (table[index] == key) {
table[index] = -1; // 将该位置置为-1,表示该位置没有元素
return;
}
index = (index + 1) % size;
}
}
};
int main() {
HashTable ht(10);
ht.insert(5);
ht.insert(15);
ht.insert(25);
ht.insert(35);
cout << ht.search(25) << endl; // 输出1,表示哈希表中存在关键字为25的元素
ht.remove(25);
cout << ht.search(25) << endl; // 输出0,表示哈希表中不存在关键字为25的元素
return 0;
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)