1. 程式人生 > >C++資料結構 20 雜湊

C++資料結構 20 雜湊

雜湊(hash_map)是最快的資料結構演算法,但是插入資料是以無序的方式插入的,所以資料是沒有排序的.

二叉樹(tree_map)比雜湊慢點(O(LogN)),但是二叉樹是以排序方式插入的(大的資料在根的右邊,小的資料在根的左邊)。

雜湊不是標準的stl,但是VS裡面可以直接包含<hash_map>直接使用

程式碼:

#ifndef __LinearMap_H__
#define __LinearMap_H__

#include <vector>

using namespace std;


template<class Key,class Value>
class LinearMap    //線性對映
{
   private:
     //  int Size;
     int CurrentSize;
     struct DateEntry
       {
          Key key;
          Value value;
         DateEntry(const Key &k=Key(),const Value &v=Value()):key(k),value(v){};
       };
       vector<DateEntry> arr;
   public:

       LinearMap(const int s=101):arr(s)
       {
         CurrentSize=0;
       }
       void Put(const Key & k,const Value & v)
       {
          arr[CurrentSize]=DateEntry(k,v);
          CurrentSize++;
       }
       Value Get(const Key &k)  //提供鍵值 返回v
       {
          for(size_t i=0;i<CurrentSize;i++)
          {
              if(arr[i].key==k)
                return arr[i].value;
          }
          return 0;
       }
};






#endif // __LinearMap_H__

#ifndef __HashMap_H__
#define __HashMap_H__

#include <vector>

using namespace std;


template<class Key,class Value>
class HashMap    //線性對映
{
   private:
     //  int Size;
     int CurrentSize;
     struct DateEntry
       {
          Key key;
          Value value;
         DateEntry(const Key &k=Key(),const Value &v=Value()):key(k),value(v){};
       };
       vector<DateEntry> arr;
   public:

       HashMap(const int s=101):arr(s)
       {
         CurrentSize=0;
       }
       void Put(const Key & k,const Value & v)
       {
          int pos = myHash(k);
          arr[pos]=DateEntry(k,v);
          ++CurrentSize;

       }
       Value Get(const Key &k)  //提供鍵值 返回v
       {
            int pos = myHash(k);
            if(arr[pos].key==k)
                return arr[pos].value;
            else
                return 0;
       }
       unsigned Hash(const Key &k)const
       {
         unsigned int hashValue=0;
         const char *keyp=reinterpret_cast<const char*>(&k);  //轉換成字元型
         for(size_t i=0;i<sizeof(Key);i++)
         {
             hashValue=37*hashValue+keyp[i];
         }
         return hashValue;
       }
       int myHash(const Key &k) const
       {
         unsigned hashValue=Hash(k);
         hashValue%=arr.size();
         return hashValue;
       }
};






#endif // __LinearMap_H__


#include <iostream>
#include "LinearMap.h"
#include "HashMap.h"
#include <string>
#include <map>  //二叉樹對映  紅黑樹 排序
#include <hash_map>  //雜湊對映 無排序
using namespace std;

int main()
{
   // cout << "Hello world!" << endl;
   LinearMap<string,int> a;
   a.Put("Bill",12);
   a.Put("dell",45);
   a.Put("Tom",78);
   cout<<a.Get("Tom")<<endl;
   HashMap<string,int> p;
  a.Put("Bill",999);
   a.Put("dell",888);
   a.Put("Tom",777);
   cout<<p.Get("dell")<<endl;

   hm["Tom"]=12;
   hm["Bill"]=100;
   cout<<hm["Tom"]<<endl;
    return 0;
}

程式碼有點問題。