标签:
原理留待。
简单hashmap类定义:
1 #include<iostream> 2 using namespace std; 3 class MySimpleHashmap 4 { 5 public: 6 int *Array; 7 enum{MaxHashSize=7}; 8 9 int hashcode(int &key); 10 11 public: 12 MySimpleHashmap(); 13 ~MySimpleHashmap(); 14 15 int& operator[](int & key); 16 17 }; 18 19 20 int& MySimpleHashmap::operator [](int& key) 21 { 22 return Array[hashcode(key)]; 23 } 24 25 26 MySimpleHashmap::MySimpleHashmap() 27 { 28 Array=new int[MaxHashSize]; 29 30 for(int i=0;i<MaxHashSize;i++) 31 { 32 Array[i]=0; 33 } 34 } 35 36 MySimpleHashmap::~MySimpleHashmap() 37 { 38 delete[] Array; 39 Array=NULL; 40 } 41 42 int MySimpleHashmap::hashcode(int& key) 43 { 44 while(true) 45 { 46 if(Array[key%MaxHashSize]==0) 47 { 48 return key%MaxHashSize; 49 } 50 else 51 { 52 key++; 53 } 54 } 55 }
main.c
1 #include "VpoetHashmap.h" 2 #include <iostream> 3 using namespace std; 4 5 int main() 6 { 7 MySimpleHashmap MyHash; 8 9 int key1=15; //hashkey=1 10 int key2=16; //hashkey=2 11 int key3=9; //hashkey=2 12 int key4=11; //hashkey=4冲突 13 int key5=5; //hashkey=5 14 15 MyHash[key1]=100; 16 MyHash[key2]=200; 17 MyHash[key3]=300; 18 MyHash[key4]=400; 19 MyHash[key5]=500; 20 21 cout<<"hash table node1:"<<MyHash.Array[0]<<endl; 22 cout<<"hash table node2:"<<MyHash.Array[1]<<endl; 23 cout<<"hash table node3:"<<MyHash.Array[2]<<endl; 24 cout<<"hash table node4:"<<MyHash.Array[3]<<endl; 25 cout<<"hash table node5:"<<MyHash.Array[4]<<endl; 26 cout<<"hash table node6:"<<MyHash.Array[5]<<endl; 27 cout<<"hash table node7:"<<MyHash.Array[6]<<endl; 28 return 0; 29 }
运行截图:
标签:
原文地址:http://www.cnblogs.com/vpoet/p/4665791.html