hashTable

This commit is contained in:
e2hang
2025-08-05 21:36:14 +08:00
parent 0ea4e65fba
commit 07f34fe0bb
2 changed files with 108 additions and 0 deletions

View File

@@ -0,0 +1,81 @@
//
// 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

27
Hash/hashArray/main.cpp Normal file
View File

@@ -0,0 +1,27 @@
#include <iostream>
#include "hashTable.h"
using namespace std;
int main() {
hashTable<string, int> table;
table.insert("start", 0);
table.insert("first", 1);
table.insert("second", 2);
table.insert("third", 3);
table.insert("fourth", 4);
table.insert("fifth", 5);
table.insert("sixth", 6);
table.insert("seven", 7);
table.insert("eight", 8);
table.insert("nine", 9);
table.insert("ten", 10);
table.insert("eleven", 11);
table.insert("twelve", 12);
table.insert("Manbo", 13);
cout << table.searchi("first") << " " << table.searchj("first") << endl;
cout << table.searchi("second") << " " << table.searchj("second") << endl;
cout << table.searchi("third") << " " << table.searchj("third") << endl;
cout << table.searchi("Manbo") << " "<< table.searchj("Manbo") << endl;
return 0;
}