哈希映射

来源:互联网 发布:淘宝联盟优惠券那里找 编辑:程序博客网 时间:2024/06/05 08:59
#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;}

0 0