哈希映射
2016-04-25 20:49
387 查看
#ifndef HASHMAP_H_ #define HASHMAP_H_ #include <vector> template<class Key, class Value> class HashMap // 哈希映射 速度最快, { public: HashMap(int size = 100) : arr(size) { currentSize = 0; } void Put(const Key & k,const Value & v) { int pos = myhash(k); arr[pos] = DataEntry(k,v); ++currentSize; } Value Get(const Key & k) { int pos = myhash(k); if(arr[pos].key == k) return arr[pos].value; else return Value(); } unsigned hash(const Key & k) const { unsigned int hashVal = 0; const char *keyp = reinterpret_cast<const char *>(&k); // 将k转变为字符, for(size_t i = 0; i < sizeof(Key); i++) hashVal = 37 * hashVal + keyp[i]; return hashVal; } int myhash(const Key & k) const { unsigned hashVal = hash(k); hashVal %= arr.size(); return hashVal; } private: struct DataEntry { Key key; Value value; DataEntry(const Key & k = Key(),const Value & v = Value()):key(k),value(v){} }; std::vector<DataEntry> arr; int currentSize; }; #endif
#ifndef LINEARMAP_H_ #define LINEARMAP_H_ #include <vector> template<class Key, class Value> class LinearMap // 线性映射 不使用, { public: LinearMap(int size = 100) : arr(size) { currentSize = 0; } void Put(const Key & k,const Value & v) { arr[currentSize] = DataEntry(k,v); ++currentSize; } Value Get(const Key & k) // 在这里可以看出它的查找速度非常的慢, { for(size_t i = 0; i < currentSize; ++i) { if(arr[i].key == k) return arr[i].value; } return Value(); } private: struct DataEntry { Key key; Value value; DataEntry(const Key & k = Key(),const Value & v = Value()):key(k),value(v){} }; std::vector<DataEntry> arr; int currentSize; }; #endif
#include <iostream> #include <map> // 映射(也叫字典),二叉树映射,不是哈希映射, #include <hash_map> // 这个是C++自己做的哈希映射,是微软做的, #include <string> #include "LinearMap.h" #include "HashMap.h" using namespace std; int main() { map<string,int> m; // 这是二叉树(红黑树)映射, m["xiaocui"] = 88; m["hengheng"] = 66; cout << m["xiaocui"] << endl; cout << "数组的优点: \n"; int a[100000]; for(int i = 0; i < 100000; ++i) a[i] = i % 100; cout << a[7] << endl; cout << a[99912] << endl; // 数组的操作是对下标进行操作,速度非常的快,直接一下找到, LinearMap<string,int> lm; lm.Put("xiaocui",1314); cout <<"LinerMap: " << lm.Get("xiaocui") << endl; cout << "哈希映射:" << endl << endl; HashMap<string,int> mymap; cout << mymap.hash("xiaocui") << endl; cout << mymap.myhash("xiaocui") << endl; mymap.Put("xiaocui",9999); mymap.Put("cuicui",88888); cout << mymap.Get("cuicui") << endl; cout << "使用C++自己做的哈希映射:" << endl; hash_map<string,int> hm; hm["xiao"] = 12; hm["cui"] = 31; cout << hm["cui"] << endl; return 0; }
相关文章推荐
- Android开发踩过的坑(一)
- C++ try catch 用法
- redis将对象序列化存储
- php发送email最终版
- Android调用WebService详解
- emacs24 配置c++ 开发环境
- CSS清除浮动大全共8种方法
- 代码之髓
- 0041 linux 下配置安装mysql以及配置
- SetupFactory打包要点集合
- 用户认证
- poj 1661 Help Jimmy(DP)
- beamer使用之ppt中插入四张图像,及中文
- Jenkins插件开发(2):开发新插件
- jQuery comet
- SOA,Webservice,SOAP,REST,RPC,RMI,JMS的区别与联系
- 第十三章 搜索
- BZOJ-2038-[2009国家集训队]小Z的袜子(hose)(莫队)
- Java——static
- 前端面试题系列