简单的闭散列(hashtable)实现(c++)
2017-08-14 13:18
441 查看
用c++实现的一个简单的闭散列,使用链表来解决slot冲突,使用移位与的方式来作为hash函数(hash函数摘自Redis源码)
#include <list> #include <iostream> #include <algorithm> #include <string> //#include <google/profiler.h> extern "C" { #include <ctype.h> #include <string.h> } template <typename T> class HashTable { private: std::list< std::pair<std::string, T> >* ht; static const int dict_hash_function_seed = 5381; int size; public: HashTable(int s) : size(s) { ht = new std::list< std::pair<std::string, T> >[size]; } /* And a caseinsensitive hash function (based on djb hash) */ //来源于Redis unsigned int dictGenCaseHashFunction(const std::string& key) { const char* buf = key.c_str(); int len = key.length(); unsigned int hash = (unsigned int)dict_hash_function_seed; while (len--) hash = ((hash << 5) + hash) +(tolower(*buf++)); /* hash * 33 + c */ return hash % size; } bool hash(const std::string &key, const T& t) { auto slot = &ht[dictGenCaseHashFunction(key)]; for(auto it = slot->begin(); it != slot->end(); it++) { if(key == it->first) { it->second = t; return true; } } slot->push_back(std::pair<std::string, T>(key, t)); return true; //std::cout<<ht[slotPos].size()<<std::endl; } bool get(const std::string& key, T& t) { auto slot = &ht[dictGenCaseHashFunction(key)]; auto it = slot->begin(); for(it = slot->begin(); it != slot->end(); it++) { if(key == it->first) { t = it->second; //std::cout<<t<<std::endl; return true; } } return false; } bool remove(const std::string& key) { auto slot = &ht[dictGenCaseHashFunction(key)]; auto it = slot->begin(); for(it = slot->begin(); it != slot->end(); it++) { if(key == it->first) { //std::cout<<it->second<<std::endl; return true; } } return false; } ~HashTable() { //ProfilerStart("profiler"); delete []ht; //ProfilerStop(); } }; int main(int argc, const char** argv) { HashTable<int> hashTable(10000000); /* for(int i = 0; i < 10000000; i++) { if(i%2 == 0) { continue; } std::string key = std::to_string(i); hashTable.hash(key, i*10); } //ProfilerStart("profiler"); for(int i = 8999999; i < 10000000; i++) { std::string key = std::to_string(i); int a = 0; hashTable.get(key, a); } //ProfilerStop(); int a = 0; hashTable.get("127", a); hashTable.hash("127", 127); hashTable.get("127", a);*/ return 0; }
相关文章推荐
- 散列表的简单实现(大话数据结构)
- Java 一个简单Hashtable的实现
- HashTable简单实现思路
- JAVA集合Hashtable实现类Properties简单练习
- HashTable(分离链接法)简单实现
- C语言的HashTable简单实现
- 用Hashtable实现简单的cache缓存
- C++复习之HashTable的简单实现
- STL 简单 hashtable 的实现
- 哈希表(hashtable)的javascript简单实现
- javascript 哈希表(hashtable)的简单实现
- 实现一个简单的HashTable
- C语言的HashTable简单实现
- HashTable的简单实现(C语言)
- hashtable简单实现
- 散列(哈希)表的C++简单操作和实现(线性探查)
- 一个简单HashTable实现,哈希函数求模取余,链地址解决冲突
- java 散列与散列码探讨 ,简单HashMap实现散列映射表执行各种操作示列
- 使用Hashtable实现简单缓存功能
- 哈希表(散列)HashTable实现