[C++]数据结构:散列表HashTable的实现与简单应用
2012-12-05 18:02
645 查看
#include <iostream> using namespace std; template<class E,class K> class HashTable{ public: HashTable(int divisor=11); ~HashTable(){delete[]ht;delete[]empty;} bool Search(const K&k,E&e)const; HashTable<E,K>& Insert(const E&e); int hSearch(const K&k)const; int D; //散列函数的除数 E *ht; //散列数组 bool *empty; //一维数组 void Output(ostream& out)const; }; //构造函数 template<class E,class K> HashTable<E,K>::HashTable(int divisor){ D = divisor; //分配散列数组 ht = new E[D]; empty=new bool[D]; //将所有桶置空 for (int i = 0;i<D;i++){ empty[i]=true; } } //查找一个开地址表 //如果存在则返回k的位置 //否则返回插入点(如果有足够的空间) //hSearch满足以下三种情况之一返回b号桶 //1)empty[b]=false且ht[b]的关键字值为k //2)表中没有关键字为k的元素,empty[b]=true,可把关键字为k的元素插入b号桶中 //3)表中没有关键字为k的元素,empty[b]为false,ht[b]的关键字值不等于k,且表已满 template<class E,class K> int HashTable<E,K>::hSearch(const K&k)const{ int i = k%D; //起始桶 int j=i; //从起始桶开始 do{ if(empty[j]||ht[j]==k) return j; j=(j+1)%D; //下一个桶 } while (j!=i); //又返回起始桶 return j; //表已经满了 } //搜索与k相匹配的元素并放入e //如果不存在则返回false template<class E,class K> bool HashTable<E,K>::Search(const K&k,E&e)const{ int b = hSearch(k); if(empty[b]||ht[b]!=k) return false; e=ht[b]; return true; } //重载操作符 template<class E,class K> ostream& operator<<(ostream& out,const HashTable<E,K>&x){ x.Output(out); return out; } //输出该跳表的内容 template<class E,class K> void HashTable<E,K>::Output(ostream& out)const { for(int i =0;i<D;i++){ if(!empty[i]) cout<<ht[i]<<" "; else cout<<"NULL"<<" "; } cout<<endl; } class BadInput{ public: BadInput(){ cout<<"Bad Input!"<<endl; } }; class NoMem{ public: NoMem(){ cout<<"No Memory!"<<endl; } }; //在散列表中插入 template<class E,class K> HashTable<E,K>& HashTable<E,K>::Insert(const E&e){ K k = e; //抽取key值 int b = hSearch(k); //检查是否能完成插入 if(empty[b]){ empty[b]=false; ht[b]=e; return *this; } if (ht[b]==k) throw BadInput(); throw NoMem(); } int main(){ HashTable<float,int>myHash; myHash.Insert(12); myHash.Insert(23); myHash.Insert(40); myHash.Insert(22); cout<<myHash<<endl; return 0; }
相关文章推荐
- [数据结构]七种排序算法的C++简单实现
- 简单数据结构之 vector 栈(C++ vector 实现)
- C# 实现C/C++共同体简单应用
- 几种简单的数据结构的C++实现,树,图,链表,环形队列,栈等---栈篇
- 简单数据结构之二叉树(C++实现)
- 简单数据结构之双向链表(C++实现)
- Java数据结构之队列的实现以及队列的应用之----简单生产者消费者应用
- 算法与数据结构基础6:C++队列的简单实现
- LoadRunner简单应用之:C++ DLL的实现及调用
- 数据结构--链式栈、顺序栈的基本实现与简单应用:进制转换
- 【数据结构】c++实现HashTable(开链法)
- 简单数据结构之队列(C++模板库实现)
- 图的简单应用(C/C++实现)
- 数据结构 hashtable C++实现 链式
- 【数据结构】c++Map的简单应用&& getline()细节
- 自己动手实现数据结构——排序算法1(冒泡、插入、归并、简单选择)(C++实现)
- 数据结构 hashtable C++实现 链式
- 程序员面试金典: 9.13 C和C++ 13.2 比较并比对散列表和STL map。散列表是如何实现的?如果输入的数据量不大,可以选用哪些数据结构替代散列表?
- 数据结构-散列表(Hash Table)的C++实现模板
- C++复习之HashTable的简单实现