转载:http://blog.csdn.net/jun362415472/article/details/4850744
C++ 版本 HashMap
#include "stdafx.h"
#include <string>
#include <iostream>
#include <fstream>
#include<vector>
using namespace std;
struct Node{
void* key ;
void* value ;
Node * next ;
};
template <typename T_key ,typename T_value>
class HashMap{
private:
const char * STRING ;
const char * CHARPOINTer;
Node* buffer[100] ;
private:
#include <typeinfo>
//#include <stdlib.h>
int hashcodef(const T_key &key){
const char * name = typeid(T_key).name();
//cout<<name<<endl;
int key1 = 0 ;
if(strcmp(name,"int") == 0
||strcmp(name,"double") == 0 ) {
key1 = *((int*)&key );
return key1%100 ;
}
if(strcmp(name,STRING )==0) {
string skey = *((string*)(&key));
for(int i = 0 ;i<skey.size() ;i++){
key1 += skey[i];
}
return key1%100 ;
}
if(strcmp(name,CHARPOINTer) == 0 ){
const char * a = *((char**)(&key ));
for(;*a;a++){
key1 += *a;
}
return key1%100 ;
}
int a =(int)&key;
// cout<<a<<endl;
return a%100 ;
}
public:
HashMap(){
for(int i = 0 ;i<100 ;i ++ ){
buffer[i] = new Node();
buffer[i]->next = NULL ;
}
STRING = "class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >";
CHARPOINTer ="char *";//注意:中间有一个空格,不然出错
}
void put(const T_key &key ,const T_value &value){
int hashcode = hashcodef(key);
//cout<<"put --HashCode = " <<hashcode<<endl;
Node * list = buffer[hashcode] ;
while(list->next)
list = list->next;
list->next = new Node();
list->next->key = new T_key[1];
*((T_key*)(list->next->key)) = key ;
list->next->value = new T_value[1];
*((T_value*)(list->next->value)) = value;
list->next->next = NULL ;
}
T_value get(const T_key &key){
int hashcode = hashcodef(key) ;
//cout<<"get --HashCode = " <<hashcode<<endl;
Node *list = buffer[hashcode] ;
while(list->next){
list = list->next ;
//bug is here . 必须针对 char * 进行处理
if(*((T_key *)(list->key)) == key){
return *((T_value *)(list->value)) ;
}
}
return NULL ;
}
};
class Own{
int a ;
public:
bool operator == (const Own &other){
return other.a == a ;
}
};
int main()
{
HashMap<int ,int > map ;
int a = 10 ;
int b = 11 ;
map.put(10 ,111) ;
cout<<map.get(10)<<endl;// //
HashMap<string,string> strmap;
strmap.put("a","b");
cout<<strmap.get("a")<<endl;
HashMap<char* ,char*> charmap ;
charmap.put("sfds","yes");
char *test= "sfds";
cout<<charmap.get(test)<<endl;
HashMap<int , string> id2name;
id2name.put(10 , "ten");
cout<<id2name.get(10)<<endl;
HashMap<Own , int> own2id;
Own own ;
own2id.put(own , 10) ;
//cout<<"Put OK"<<endl;
//cout<<"Main"<<(int)(&own)<<endl;
cout<<own2id.get(own)<<endl;
char * ca = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
int *afsfs = new int[10];
char * cb = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
char *arr = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
cb = arr;
if(ca == cb){
//output,说明在文字常量区只保存了一份 aaa...aaa,算是编译器的一个优化吧。
cout<<"Amazing"<<endl;
cout<<(int)&ca<<endl;
cout<<(int)&cb<<endl;
}
cout<<sizeof(char*)<<endl;
return 0;
}