您的位置:首页 > 编程语言 > C语言/C++

简单的闭散列(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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hashtable c++ 散列