1. 程式人生 > >C++資料結構--.雜湊表線性探測開放定址法與獨立錶鏈地址法

C++資料結構--.雜湊表線性探測開放定址法與獨立錶鏈地址法


class hashTable
{
friend class hashIterator;
private:
vector<list<T>> table; 
hashFun fun;
 //雜湊函式物件
size_t rows;    
public:
#include"hashIterator.h"  //詳見C++資料結構--.雜湊表獨立錶鏈地址法迭代器的設計
hashTable(size_t r,hashFun hf=hashFun()):table(r),rows(r),fun(hf){}

//查詢val所在的迭代器位置 
hashIterator find(const T &val)
{

int r=fun(val)%rows;//用雜湊函式定位 
if(table[r].empty()) //val不存在雜湊表中,返回end() 
{

return hashIterator(this,-1,table[r].end());
}
else
{
  typenamelist<T>::iterator it=table[r].begin();
  for(;it!=table[r].end();it++)//遍歷雜湊函式定位的行
  {
 if(*it==val)
   return hashIterator(this,r,it);
  }
return hashIterator(this,-1,table[r].end());
//不存在val,返回end() 
}
}

//插入val,返回 hashIterator-bool鍵值對 
pair<hashIterator , bool> insert(const T &val)
{
hashIterator hit=find(val);//查詢val所在的迭代器位置 
size_t r=fun(val)%rows;//用雜湊函式定位
bool success=false; //查詢是否成功標誌 
if(hit.row==-1) //當val不存在雜湊表時,插入val 
{
typename list<T>::iterator it=table[r].end();
it=table[r].insert(it,val);

success=true;
return make_pair(hashIterator(this,r,it),success);
}

return make_pair(hit,success);//當val存在雜湊表時,返回val所在迭代器位置,但不插入 

}


//刪除val 
void erase(const T &val)
{
hashIterator hit=find(val);
size_t r=fun(val)%rows;
if(hit.row==-1) //val不存在雜湊表示,刪除非法 
{
cerr<<"value "<<val<<" is not exist,can't erase"<<endl;
return;
}

table[r].erase(hit.it);

}

//刪除迭代器指定的位置 
void erase(hashIterator pos)
            {
if(pos==end())//刪除end(),非法 
 {
cerr<<"can't erase end()"<<endl;
return;
 } 

           T val=*pos;
           erase(val);

        }

//返回第一個元素所在的迭代器位置
hashIterator begin()
{
for(int i=0;i<rows;i++)
 {
 if(!table[i].empty())
  return hashIterator(this,i,table[i].begin());
 }

 return hashIterator(this,-1,table[0].end()); //雜湊表為空時返回end() 
}

//返回end()迭代器 
hashIterator end()
{
return hashIterator(this,-1,table[0].end());
}



};