按照hashmap的基本原理用C++实现了简单的基本功能,复杂的实现参考C++库的源码,C++最新的标准库里已经有以下四种基于hashtable的容器:
unordered_set (C++11) unordered_multiset (C++11) unordered_map (C++11) unordered_multimap (C++11)。
/*
* HashMap.h
* Author: luxiaoxun
*/
#ifndef HASHMAP_H_
#define HASHMAP_H_
#include <iostream>
using namespace std;
//List all the integer number no less than 57 total number is 28
//And each number is about half of its next number
static int prime[28] =
{
57, 97, 193, 389, 769,
1543, 3079, 6151, 12289, 24593,
49157, 98317, 196613, 393241, 786433,
1572869, 3145739, 6291469, 12582917, 25165843,
50331653, 100663319, 201326611, 402653189, 805306457,
1610612741
};
class HashMapUtil
{
public:
static int find_NextPrimeNumber(int current)
{
//Find the next prime number by searching in the prime number list
int i = 0;
for( ; i < 28 ; i++ )
if(current < prime[i])
break;
return prime[i]; //return the next larger prime.
}
};
template <class Key, class Value, class HashFunc, class EqualKey>
class HashMap
{
private:
template <class _Key, class _Value>
class KeyNode
{
public:
_Value value; //Store the value
_Key key; //Store the keyword
int used;
//if the type of Value/Key is your own class, make sure they can handle copy constructor and operator =
KeyNode():used(0){}
KeyNode(const KeyNode & kn)
{
value = kn.value;
key = kn.key;
used = kn.used;
}
KeyNode & operator=(const KeyNode & k