哈希表C++实现(大概模型,有些细节没有考虑)
来源:互联网 发布:网络114推广 编辑:程序博客网 时间:2024/06/05 09:58
//HashTable.h#include <string>using std::string;struct node{ int data; node* next; node() { data = INT_MAX; next = NULL; }};class HashTable{public: HashTable(); HashTable(int); ~HashTable(); int& operator[](const string); void SetValue(const string, int);private:` int RSHash(const string); int size; node* ht;};
//HashTable.cpp#include <exception>#include "HashTable.h"using std::string;HashTable::HashTable(){ ht = NULL; size = 0;};HashTable::HashTable(int ht_size){ size = ht_size; ht = new node[ht_size](); //nothrow};HashTable::~HashTable(){ if (ht != NULL) delete ht;};int HashTable::RSHash(const string key){ unsigned int b = 378551; unsigned int a = 63689; unsigned int hash = 0; for (int i = 0; i < key.size(); ++i) { hash = hash * a + key[i]; a *= b; } return (hash & 0x7FFFFFFF) % size;};int& HashTable::operator[](const string key){ node* res = ht[RSHash(key)].next; if (res != NULL) return res->data; else throw "Error: given key does not have a value!";};void HashTable::SetValue(const string key, int value){ node* cur = &ht[RSHash(key)]; while (cur->next != NULL) cur = cur->next; cur->next = new node(); cur->next->data = value;};
//main.cpp#include <iostream>#include <string>#include <exception>#include "HashTable.h"using std::string;using std::cout;int main(){ HashTable* ht = new HashTable(100); ht->SetValue("Hit", 1); ht->SetValue("Make", 2); cout << (*ht)["Hit"] << std::endl; cout << (*ht)["Make"] << std::endl; return 0;}