哈希表
来源:互联网 发布:centos 中英输入法转换 编辑:程序博客网 时间:2024/06/16 12:04
哈希表又叫散列表,关键值通过哈希函数映射到数组上,查找时通过关键值直接访问数组。
#include <iostream>#include <string>using namespace std;class HashTable {private: string *elem; int size;public: HashTable() { size = 2000; elem = new string[size]; for (int i = 0; i < size; i++) { elem[i] = "#"; } } ~HashTable() { delete[] elem; } int hash(string& index) { int code = 0; for (size_t i = 0; i < index.length(); i++) { code = (code * 256 + index[i] + 128) % size; } return code; } bool search(string& index, int& pos, int& times) { pos = hash(index); times = 0; while (elem[pos] != "#" && elem[pos] != index) { times++; if (times < size) { pos = (pos + 1) % size; } else { return false; } } if (elem[pos] == index) { return true; } else { return false; } } int insert(string& index) { int pos, times; if (search(index, pos, times)) { return 2; } else if (times < size / 2) { elem[pos] = index; return 1; } else { recreate(); return 0; } } void recreate(){ string * temp_elem; temp_elem = new string[size]; for(int i=0;i<size;i++){ temp_elem[i]=elem[i]; } int copy_size=size; size*=2; delete[] elem; elem = new string[size]; for(int i=0;i<size;i++){ elem[i]="#"; } for(int i=0;i<copy_size;i++){ if(temp_elem[i]!="#"){ insert(temp_elem[i]); } } delete[] temp_elem; }};int main() { HashTable hashtable; string buffer; int n; cin >> n; for (int i = 1; i <= n; i++) { cin >> buffer; int ans = hashtable.insert(buffer); if (ans == 0) { cout << "insert failed!" << endl; } else if (ans == 1) { cout << "insert success!" << endl; } else if (ans == 2) { cout << "It already exists!" << endl; } } int temp_pos, temp_times; cin >> buffer; if (hashtable.search(buffer, temp_pos, temp_times)) { cout << "search success!" << endl; } else { cout << "search failed!" << endl; } return 0;}
0 0
- 哈希表
- 哈希表
- 哈希表
- 哈希表
- 哈希表
- .哈希表
- 哈希表
- 哈希表
- 哈希表
- 哈希表
- 哈希表
- 哈希表
- 哈希表
- 哈希表
- 哈希表
- 哈希表
- 哈希表
- 哈希表
- JVM内存管理
- lcs 入门题 模板
- LeetCode 345 反转元音字符串
- 第八周上机实践项目 项目2-用对象数组操作长方柱类
- socket函数1
- 哈希表
- 高光谱遥感图像处理(11)----ENVI建立矢量数据
- [BZOJ2060][Usaco2010 Nov]Visiting Cows 拜访奶牛(树形dp)
- Androidn Notification的使用,解决找不到setLatestEventInfo方法
- FormData实现异步传送带文件的表单
- 121. Best Time to Buy and Sell Stock
- 【日常小记】linux中强大且常用命令:find、grep
- int和Integer有什么区别?
- socket服务器代码