zoukankan      html  css  js  c++  java
  • (数据结构)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;
    }
  • 相关阅读:
    01-Git 及其可视化工具TortoiseGit 的安装和使用
    IntelliJ IDEA中Warning:java:源值1.5已过时, 将在未来所有发行版中删除
    JVM学习笔记四_垃圾收集器与内存分配策略
    JVM学习笔记三_异常初步
    CentOs7 图形界面和命令行界面切换
    基本概念一
    JVM学习笔记二_对象的创建、布局和定位
    JVM学习笔记一_运行时数据区域
    个人阅读作业二
    软件工程随笔
  • 原文地址:https://www.cnblogs.com/Numblzw/p/10022787.html
Copyright © 2011-2022 走看看