标签:哈希函数 create target logs [] false 函数 == while
哈希表中,关键值通过哈希函数映射到数组上,查找时通过关键值直接访问数组。哈希表的关键问题在于哈希函数的构造和解决冲突的方法。
下面采用最简单的线性探测展示一下哈希表的基本操作:
1 //Hashtable 2 class HashTable { 3 private: 4 string *elem; 5 int size; 6 public: 7 HashTable() { 8 size = 2000; 9 elem = new string[size]; 10 for (int i = 0; i < size; i++) { 11 // "#" means that this slot is empty 12 elem[i] = "#"; 13 } 14 } 15 ~HashTable() { 16 delete[] elem; 17 } 18 19 // get hash code of a string 20 int hash(string &value) { 21 int code = 0; 22 for (size_t i = 0; i < value.length(); i++) { 23 code = (code * 256 + value[i] + 128) % size; 24 } 25 return code; 26 } 27 28 //search for an element 29 //here pos and times are reference, 30 //so in the end pos will be set to the pos of the target and times and how many slots you have tried 31 bool search(string &value, int &pos, int ×) { 32 pos = hash(value); 33 times = 0; 34 while (elem[pos] != "#" && elem[pos] != value) { 35 times++; 36 if (times < size) { 37 //test for next slot 38 pos = (pos + 1) % size; 39 } else { 40 return false; 41 } 42 } 43 if (elem[pos] == value) { 44 return true; 45 } else { 46 //the slot is vacant 47 return false; 48 } 49 } 50 51 int insert(string &value) { 52 int pos, times; 53 if (search(value, pos, times)) { 54 //the elem already exists 55 return 2; 56 } else if (times < size / 2) { 57 elem[pos] = value; 58 return 1; 59 } else { 60 //the hashtable is too packed, need to expand and make it sparse 61 recreate(); 62 insert(value); 63 return 0; 64 } 65 } 66 67 void recreate(){ 68 string *temp_elem; 69 temp_elem=new string[size]; 70 for(int i=0;i<size;i++){ 71 temp_elem[i]=elem[i]; 72 } 73 int copy_size=size; 74 size=size*2; 75 delete[] elem; 76 elem=new string[size]; 77 for(int i=0;i<size;i++){ 78 elem[i]="#"; 79 } 80 for(int i=0;i<copy_size;i++){ 81 if(temp_elem[i]!="#"){ 82 insert(temp_elem[i]); 83 } 84 } 85 delete[] temp_elem; 86 } 87 }; 88 89 int main() { 90 HashTable hashtable; 91 string buffer; 92 int n; 93 cin >> n; 94 for (int i = 1; i <= n; i++) { 95 cin >> buffer; 96 int ans = hashtable.insert(buffer); 97 if (ans == 0) { 98 cout << "recreate while insert!" << endl; 99 } else if (ans == 1) { 100 cout << "insert success!" << endl; 101 } else if (ans == 2) { 102 cout << "It already exists!" << endl; 103 } 104 } 105 int temp_pos, temp_times; 106 cin >> buffer; 107 if (hashtable.search(buffer, temp_pos, temp_times)) { 108 cout << "search success!" << endl; 109 } else { 110 cout << "search failed!" << endl; 111 } 112 return 0; 113 }
标签:哈希函数 create target logs [] false 函数 == while
原文地址:http://www.cnblogs.com/NoviScl/p/7128645.html