• (数据结构)HashTable的实现


    #include<iostream>
    #include<iomanip>
    #include<vector>
    #include<list>
    using namespace std;
    template<class Iterator,class T>
    Iterator Find(Iterator first,Iterator last,const T& x)
    {
     while(first!=last&&*first!=x)
     {
      ++first;
     }
     return first;
    }
    template<class T>
    class HashTable
    {
    private:
     int nt;
     vector<list<T> > ht;
     int size;
     int (*hf)(const T& x);
    public:
     explicit HashTable(int n,int (*hash)(const T& x)):nt(n),hf(hash),size(0){ht.resize(n);}
     bool Insert(const T& x);
     bool Remove(const T& x);
     bool Find(const T& x)const;
     int Size()const{return size;}
     int Empty()const{return size==0;}
     int NumberOfBucket()const{return nt;}
     friend std::ostream& operator<<(std::ostream& ostr,const HashTable<T>& ht)
     {
         int n=ht.NumberOfBucket();
         list<T>::const_iterator first,last;
      for(int i=0;i<n;i++)
      {
       first=ht.ht[i].begin(),last=ht.ht[i].end();
       for(;first!=last;++first)
       {
        cout<<setw(4)<<*first<<' ';
       }
       cout<<endl;
      }
      return ostr;
     }
    };
    template<class T>
    bool HashTable<T>::Insert(const T& x)
    {
     list<T>& L=ht[hf(x)];
     if(::Find(L.begin(),L.end(),x)!=L.end())
     {
      return 0;
     }
     L.push_back(x);
     size++;
     return 1;
    }
    template<class T>
    bool HashTable<T>::Remove(const T& x)
    {
     list<T>& L=ht[hf(x)];
     list<T>::iterator itr=::Find(L.begin(),L.end(),x);
     if(itr==L.end())
     {
      return 0;
     }
     L.erase(itr);
     size--;
     return 1;
    }
    template<class T>
    bool HashTable<T>::Find(const T& x)const
    {
     const list<T>& L=ht[hf(x)];
     if(::Find(L.begin(),L.end(),x)!=L.end())
     {
      return 1;
     }
     return 0;
    }
    int hf(const int & key)
    {
     return key%7;
    }
    int main()
    {
     HashTable<int> HT(7,hf);
     for(int i=0;i<=27;i++)
     {
      HT.Insert(i);
     }
     cout<<(HashTable<int>)HT;
     cout<<"after removing:"<<endl;
     if(HT.Find(20))
     {
      HT.Remove(20);
     }
     cout<<HT<<endl;
     return 0;
    }
  • 相关阅读:
    Js 作用域链
    JS 上下文模式
    javascript
    HTTP概念进阶
    JavaScript运行机制详解
    浅谈循环中setTimeout执行顺序问题
    Js 运行机制 (重点!!)
    javascript
    jQuery 知识点总结
    Educational Codeforces Round 87 (Rated for Div. 2)
  • 原文地址:https://www.cnblogs.com/Numblzw/p/10022787.html
Copyright © 2020-2023  润新知