Files
Data-Structure/Hash/hashArray/hashTable.h
2025-08-05 21:36:14 +08:00

82 lines
1.9 KiB
C++

//
// Created by E2hang on 2025/8/5.
//
#ifndef HASHTABLE_H
#define HASHTABLE_H
#include <functional>
#include <vector>
template<class K, class E>
class hashTable {
private:
std::hash<K> hashFunc;
std::vector<std::vector<std::pair<K, E>>> table;
int dsize;
int division;
public:
hashTable(int d = 1009);
~hashTable() = default;
//hashTable(const hashTable<K, E>&);
int searchj(const K &key);
int searchi(const K &key) {return hashFunc(key) % division;};
void insert(const K& key, const E& e);
void erase(const K& key);
std::pair<K, E>* find(const K& key);
};
template<class K, class E>
hashTable<K, E>::hashTable(int d) : dsize(0), division(d) {
table.resize(d);
}
template<class K, class E>
int hashTable<K, E>::searchj(const K &key) {
int i = static_cast<int>(hashFunc(key) % division);
int j = 0;
for (std::pair<K, E> x : table[i]) {
if (x.first == key ) return j;
j++;
}
return -1;
}
template<class K, class E>
void hashTable<K, E>::insert(const K &key, const E &e) {
int i = static_cast<int>(hashFunc(key) % division);
for (auto &x : table[i]) {
if (x.first == key) {
x.second = e;
return;
}
}
table[i].push_back(std::make_pair(key, e));
}
template<class K, class E>
void hashTable<K, E>::erase(const K &key) {
int i = static_cast<int>(hashFunc(key) % division);
auto &bucket = table[i];
for (auto it = bucket.begin(); it != bucket.end(); ++it) {
if (it->first == key) {
bucket.erase(it);
return; // 删除后退出
}
}
}
template<class K, class E>
std::pair<K, E>* hashTable<K, E>::find(const K &key) {
int i = static_cast<int>(hashFunc(key) % division);
int j = searchj(key);
if (j == -1) {
return nullptr; // 找不到返回 nullptr
}
return &table[i][j];
}
#endif //HASHTABLE_H