哈希表是一种基于键值映射的快速搜索的数据结构,时间复杂度基本上是O(1)。针对键与值的映射,我们通过哈希函数(散列函数)来实现,它大致有数字分析法、平方取中法、折叠法、除留余数法等,而除留余数法对我们来说最为常见,也更适合初学者理解。但是在取余的过程中可能会导致散列冲突,在这里先用开放定址法中的线性探测法实现。
哈希表目前在STL中的实现是unorder_map,非常好用,今天试着自己实现一个:
#include <iostream>
#include <vector>
using namespace std;
template <typename K, typename V>
class HashNode
{
public:
HashNode(const K& key = K(), const V& value = V())
{
key_ = key;
value_ = value;
}
K key_;
V value_;
bool initialized_ = false;
};
template <typename K, typename V>
class HashTable
{
public:
HashTable(int size)
{
node_num_ = 0;
nodes_.resize(size);
}
int hashFunction(const K& key)
{
return hash_index_ % hash(key);
}
V find(const K& key)
{
int index = hashFunction(key);
while(nodes_[index].initialized_)
{
if(nodes_[index].key_ == key)
{
return nodes_[index].value_;
}
index++;
if(index == node_num_)
{
index = 0;
}
}
}
void insert(const K& key, const V& value)
{
/* 当哈希表的长度不够用时,应该进行扩容,设立一个扩容长度表 */
int index = hashFunction(key);
while(nodes_[index].initialized_)
{
index++;
if(index == node_num_)
{
index = 0;
}
}
nodes_[index].key_ = key;
nodes_[index].value_ = value;
nodes_[index].initialized_ = true;
}
int hash(const K& key)
{
return key;
}
private:
std::vector<HashNode<K, V> > nodes_;
int node_num_;
int hash_index_;
};
int main(int argc, char** argv)
{
HashTable<int, int> table(10);
table.insert(1, 8);
table.insert(2, 10);
table.insert(3, 18);
table.insert(4, 5);
cout<<table.find(3)<<endl;
return 0;
}
在这里还没有复现所有的API,也没有对地址冲突进行下一步的处理,未完待续。。。