1. 程式人生 > >自己動手用c++實現雜湊表

自己動手用c++實現雜湊表

雜湊表

  • 查詢效率約等於1

實現思想介紹

  • 一般的hash思想
  • 未採用模板,簡單的實現
  • key是int,value是string
  • 把輸入的key值經過hash函式計算,算出它要放入的桶的編號
  • 採用一個指標陣列記錄各個桶
  • 每個桶裡都有50個key_value物件,這裡未採用連結串列,只是用陣列簡單那模擬

缺點

  • batch類設計的有問題,沒采用連結串列,不能動態增加
  • insert方法,不能改變已有的key-value,只能插入
  • and so on~不足有很多,望多多包涵。

程式碼

// HashTable.cpp : Defines the entry point for the console application.
// #include "stdafx.h" #include <iostream> #include <string> using namespace std; struct key_value { int key;//預設許可權是public string value; key_value(){//初始值選取不太好 key = 0; value = "0"; } }; class Batch {//類設計不完善,應該是可以動態新增桶的長度,所以用連結串列最好。我這裡懶,直接用陣列模擬。 public: Batch(){ current_batchsize =
-1; } int current_batchsize; public: key_value k_v[50]; }; class HashTable { public: HashTable(){ init(); } Batch* batch[10]; public: void init(); int hash(int); key_value lookup(int); void insert(int, string); }; void HashTable::init() { for (int i=0; i<10; ++i) { batch[i]= new Batch
(); } } int HashTable::hash(int input) { return input%10; } key_value HashTable::lookup(int key) { int batch_num = hash(key); for (int i=0;i<50;++i) { if (batch[batch_num]->k_v[i].key == key) { return batch[batch_num]->k_v[i]; } } } void HashTable::insert(int key, string value) { int batch_num = hash(key); int current_batchsize = batch[batch_num]->current_batchsize; //有問題,若是有相同的key,應該是改變他的value batch[batch_num]->k_v[current_batchsize+1].key = key; batch[batch_num]->k_v[current_batchsize+1].value = value; batch[batch_num]->current_batchsize++; } int _tmain(int argc, _TCHAR* argv[]) { HashTable my_hash_table; int a =1,b=2,c=3,d=11; my_hash_table.insert(a,"a"); my_hash_table.insert(b,"b"); my_hash_table.insert(c,"c"); my_hash_table.insert(d,"d"); cout<<"batch_num:"<<my_hash_table.hash(a)<<" key:"<<my_hash_table.lookup(a).key<<" value:"<<my_hash_table.lookup(a).value<<endl; cout<<"batch_num:"<<my_hash_table.hash(b)<<" key:"<<my_hash_table.lookup(b).key<<" value:"<<my_hash_table.lookup(b).value<<endl; cout<<"batch_num:"<<my_hash_table.hash(c)<<" key:"<<my_hash_table.lookup(c).key<<" value:"<<my_hash_table.lookup(c).value<<endl; cout<<"batch_num:"<<my_hash_table.hash(d)<<" key:"<<my_hash_table.lookup(d).key<<" value:"<<my_hash_table.lookup(d).value<<endl; system("pause"); return 0; }