?? hashdict.cpp
字號:
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
#include "Int.h"
#include "..\compare.h"
#include "hashdict.h"
// 檢索關鍵碼值為k的記錄。假定每個關鍵碼的探查序列中
//至少有一個槽是空的,否則它們就會進入一個無限循環中。
template <class Key, class Elem, class KEComp, class EEComp>
bool hashdict<Key, Elem, KEComp, EEComp>::
hashSearch(const Key& K, Elem& e) const {
int home= h(K); // home 保存K的基地址
int i=0;
int pos = home; // 探查序列的初始位置
while(!EEComp::eq(EMPTY, HT[pos])){
if (KEComp::eq(K, HT[pos])) { // 發現目標
e = HT[pos];
return true;
}
i++;
pos = (home + p(K, i)) % M;
}
return false;
}
// 將數據元素e插入到散列表 HT
template <class Key, class Elem, class KEComp, class EEComp>
bool hashdict<Key, Elem, KEComp, EEComp>::hashInsert(const Elem &e)
{
int home= h(getkey(e)); // home記錄基位置
int i=0;
int pos = home; // 探查序列的初始位置
while(!EEComp::eq(EMPTY, HT[pos])
&& !EEComp::eq(TOMB, HT[pos])){
if (KEComp::eq(getkey(e), HT[pos]))
return false; //不允許重復關鍵碼
i++;
pos = (home + p(getkey(e), i)) % M;
}
HT[pos]=e; //插入e
return true;
}
// 刪除函數
template <class Key, class Elem, class KEComp, class EEComp>
Elem hashdict<Key,Elem,KEComp,EEComp>::hashDelete(const Key& K)
{
int home= h(K); // home記錄基位置
int i=0;
int pos = home; // 探查序列的初始位置
while(!EEComp::eq(EMPTY, HT[pos])){
if (KEComp::eq(K, HT[pos])){
temp = HT[pos];
HT[pos] = TOMB; //設置墓碑
return temp; //返回目標
}
i++;
pos = (home + p(K, i)) % M;
}
return EMPTY;
}
int getkey(Int* e)
{
return e->key();
}
char* getkey(char* e)
{
return e;
}
int Intkey(Int& e)
{
return e.key();
}
char* charkey(char*& e)
{
return e;
}
void main(int argc, char** argv) {
hashdict<int, Int*, intIntsCompare, IntsIntsCompare> dict(100, new Int(-1),new Int(-2));
Int* val;
dict.hashInsert(new Int(10));
if (dict.hashSearch(10, val))
cout << "發現值 " << val << " 匹配關鍵碼10\n";
else
cout << "沒有發現匹配關鍵碼10的元素\n";
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -