#include <iostream>
#include <cstring>
#include <string>
typedef unsigned int SIZE_T;
using namespace std; /** HashMap模板的C++实现,用拉链法解决冲突
*注意:需要为每一种KeyType两个仿函数:HashFunc and EqualKey
*/ template<typename KeyType, typename ValueType, typename HashFunc, typename EqualKey>
class HashMap{
#define DEFAULT_CAPACITY 43 // hash表初始化容量
#define LOADFACTOR 0.7 //负载因子 class KeyNode{ //存放key value对
public:
KeyType key;
ValueType value;
KeyNode *next;
KeyNode(){}
KeyNode(const KeyNode & rhs){
Assign(rhs);
}
const KeyNode & operator =(const KeyNode & rhs){
Assign(rhs);
return *this;
}
void Assign(const KeyNode & rhs){
this->key = rhs.key;
this->value = rhs.value;
this->next = rhs.next;
}
};
public:
HashMap(){
table = new KeyNode* [DEFAULT_CAPACITY];
::memset(table,,DEFAULT_CAPACITY * sizeof(KeyNode*));
size =;
capacity = DEFAULT_CAPACITY;
hash = HashFunc();
equal = EqualKey();
}
bool put(const KeyType & key, const ValueType & value){
SIZE_T index = hash(key) % capacity;
if(table[index] == NULL){
KeyNode *temp = new KeyNode();
temp->key = key;
temp->value = value;
temp->next =NULL;
table[index] = temp; }else{
KeyNode * pre=table[index]; while(pre->next != NULL){
if(equal(pre->key, key)) return false; //重复
pre = pre->next;
}
if(equal(pre->key, key)) return false; //重复
KeyNode *temp = new KeyNode();
temp->key = key;
temp->value = value;
temp->next =NULL;
pre->next = temp;
}
size ++;
if(size*1.0/capacity > LOADFACTOR) this->rehash();
return true;
}
bool remove(const KeyType & key){
SIZE_T index = hash(key) % capacity;
if(table[index] == NULL) return false;
KeyNode *temp = table[index];
if(equal(temp->key,key)){
table[index] = temp->next;
delete temp;
size --;
return true;
}
while(temp->next != NULL){
if(equal(temp->next->key, key)){
KeyNode * del = temp->next;
temp->next = del->next;
delete del;
size --;
return true;
}else{
temp = temp->next;
}
}
return false;
}
bool exist(const KeyType & key)const{
SIZE_T index = hash(key) % capacity;
if(table[index] == NULL) return false;
KeyNode *temp = table[index];
while(temp!= NULL){
if(equal(temp->key,key)) return true;
temp = temp->next;
}
return false;
}
/*
KeyNode find(const KeyType & key){
SIZE_T index = hash(key) % capacity;
if(table[index] == NULL) return NULL;
KeyNode *temp = table[index];
while(temp!= NULL){
if(equal(temp->key,key)) return *temp;
temp = temp->next;
}
return NULL;
}
*/
ValueType & operator[](const KeyType & key){
if(!exist(key)) put(key,ValueType());
return get(key);
}
SIZE_T Size(){
return size;
}
void display(){
cout << "size:"<<size<<endl;
for(SIZE_T i=;i<this->capacity;i++){
KeyNode * temp = table[i];
while(temp != NULL){
cout <<"("<<temp->key<<","<<temp->value<<") ";
temp = temp->next;
}
if(table[i]!=NULL) cout << endl;
}
}
~HashMap(){
this->destroy(table);
} private:
KeyNode ** table;
SIZE_T capacity;
SIZE_T size;
HashFunc hash;
EqualKey equal;
KeyNode ERROE; ValueType & get(const KeyType key){
SIZE_T index = hash(key) % capacity;
if(table[index] == NULL) return ERROE.value;
KeyNode *temp = table[index];
while(temp!= NULL){
if(equal(temp->key,key)) return temp->value;
temp = temp->next;
}
return ERROE.value;
}
//未实现
void rehash(){
//得到一个两倍左右大小的capacity(最好为素数),重新散列
}
void destroy(KeyNode ** hashtable){
for(SIZE_T i=;i<this->capacity;i++){
KeyNode * temp = hashtable[i];
while(temp != NULL){
KeyNode *del = temp;
temp = temp->next;
delete del;
}
}
delete []hashtable;
}
}; class HashFuncInt{
public:
SIZE_T operator()( int key)const{
return key;
}
}; class EqualFuncInt{
public:
bool operator()(int keyA, int keyB)const{
return keyA == keyB;
}
}; int main()
{
const int scale = ;
//内存泄露性能测试
while(false){
HashMap<int,int,HashFuncInt,EqualFuncInt> hm;
for(int i=;i<scale;i++){
hm.put(i,i*(i+));
}
hm.display();
for(int i=;i<scale;i+=)
hm.remove(i);
hm.display();
for(int i=;i<scale;i+=)
hm[i]=i*;
hm.display();
} //模板实用性测试 return ;
}

参考文献:

HashMap的C++实现的更多相关文章

  1. HashMap与TreeMap源码分析

    1. 引言     在红黑树--算法导论(15)中学习了红黑树的原理.本来打算自己来试着实现一下,然而在看了JDK(1.8.0)TreeMap的源码后恍然发现原来它就是利用红黑树实现的(很惭愧学了Ja ...

  2. HashMap的工作原理

    HashMap的工作原理   HashMap的工作原理是近年来常见的Java面试题.几乎每个Java程序员都知道HashMap,都知道哪里要用HashMap,知道HashTable和HashMap之间 ...

  3. 计算机程序的思维逻辑 (40) - 剖析HashMap

    前面两节介绍了ArrayList和LinkedList,它们的一个共同特点是,查找元素的效率都比较低,都需要逐个进行比较,本节介绍HashMap,它的查找效率则要高的多,HashMap是什么?怎么用? ...

  4. Java集合专题总结(1):HashMap 和 HashTable 源码学习和面试总结

    2017年的秋招彻底结束了,感觉Java上面的最常见的集合相关的问题就是hash--系列和一些常用并发集合和队列,堆等结合算法一起考察,不完全统计,本人经历:先后百度.唯品会.58同城.新浪微博.趣分 ...

  5. 学习Redis你必须了解的数据结构——HashMap实现

    本文版权归博客园和作者吴双本人共同所有,转载和爬虫请注明原文链接博客园蜗牛 cnblogs.com\tdws . 首先提供一种获取hashCode的方法,是一种比较受欢迎的方式,该方法参照了一位园友的 ...

  6. HashMap与HashTable的区别

    HashMap和HashSet的区别是Java面试中最常被问到的问题.如果没有涉及到Collection框架以及多线程的面试,可以说是不完整.而Collection框架的问题不涉及到HashSet和H ...

  7. JDK1.8 HashMap 源码分析

    一.概述 以键值对的形式存储,是基于Map接口的实现,可以接收null的键值,不保证有序(比如插入顺序),存储着Entry(hash, key, value, next)对象. 二.示例 public ...

  8. HashMap 源码解析

    HashMap简介: HashMap在日常的开发中应用的非常之广泛,它是基于Hash表,实现了Map接口,以键值对(key-value)形式进行数据存储,HashMap在数据结构上使用的是数组+链表. ...

  9. java面试题——HashMap和Hashtable 的区别

    一.HashMap 和Hashtable 的区别 我们先看2个类的定义 public class Hashtable extends Dictionary implements Map, Clonea ...

  10. 再谈HashMap

    HashMap是一个高效通用的数据结构,它在每一个Java程序中都随处可见.先来介绍些基础知识.你可能也知 道,HashMap使用key的hashCode()和equals()方法来将值划分到不同的桶 ...

随机推荐

  1. c#ADSL拨号类

    class ADSLHelper { /// <summary> ///拨号 /// </summary> /// <param name="connectio ...

  2. 在CentOS上源码安装Nginx

    总步骤: wget http://nginx.org/download/nginx-1.10.1.tar.gz tar -xvf nginx-1.10.1.tar.gz cd nginx-1.10.1 ...

  3. ajax在购物车中的应用

    代码如下: 购物车页面: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http: ...

  4. 小白学phoneGap《构建跨平台APP:phoneGap移动应用实战》连载三(通过实例来体验生命周期)

    4.1.2  通过实例来亲身体验Activity的生命周期 上一小节介绍了Activity生命周期中的各个过程,本小节将以一个简单的实例来使读者亲身体验到Activity生命周期中的各个事件. 在Ec ...

  5. npm使用快速的安装源(nrm)

    安装 npm install nrm --global 使用 nrm ls 切换安装源 nrm use taobao 测速 nrm test npm 参考地址:http://codingdict.co ...

  6. Java 反射机制(一)

    阅读<Core Java Volume I --- Fundamentals>反射部分,总觉得许多概念艰涩难懂.模棱两可.我想造成这个结果的主要原因可能是Cay S. Horstmann和 ...

  7. BZOJ 1806: [Ioi2007]Miners 矿工配餐

    ime Limit: 10 Sec  Memory Limit: 64 MBSubmit: 910  Solved: 559[Submit][Status][Discuss] Description ...

  8. jquery的uploadify插件实现的批量上传V3.2.1版

    你需要如下配置(包括引入文件)HTML: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat=&quo ...

  9. 爬虫遇到HTTP Error 403的问题

    # coding=gbk from bs4 import BeautifulSoup import requests import urllib x = 1 y = 1 def crawl(url): ...

  10. Silverlight日记:动态生成DataGrid、行列装换、动态加载控件

    本文主要针对使用DataGrid动态绑定数据对象,并实现行列转换效果. 一,前台绑定 <sdk:DataGrid x:Name="dataGrid2" Style=" ...