?? hashdict.cpp
字號:
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
#include "Int.h"
#include "..\compare.h"
#include "hashdict.h"
// 檢索關(guān)鍵碼值為k的記錄。假定每個關(guān)鍵碼的探查序列中
//至少有一個槽是空的,否則它們就會進入一個無限循環(huán)中。
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])) { // 發(fā)現(xiàn)目標(biāo)
e = HT[pos];
return true;
}
i++;
pos = (home + p(K, i)) % M;
}
return false;
}
int getkey(Int* e)
{
return e->key();
}
char* getkey(char* e)
{
return e;
}
// 將數(shù)據(jù)元素e插入到散列表 HT
template <class Key, class Elem, class KEComp, class EEComp>
bool hashdict<Key, Elem, KEComp, EEComp>::
hashInsert(const Elem& e) {
int home; //home存儲基位置
int i=0;
int pos = home= h(getkey(e)); //初始化探查序列
while(!EEComp::eq(EMPTY, HT[pos])){
if (EEComp::eq(e, HT[pos]))
return false; // 發(fā)現(xiàn)重復(fù), 返回
i++;
pos = (home + p(getkey(e), i)) % M; // 繼續(xù)向前探查
}
HT[pos] = e; // 插入元素e
return true;
}
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));
Int* val;
dict.hashInsert(new Int(10));
if (dict.hashSearch(10, val))
cout << "發(fā)現(xiàn)值 " << val << " 匹配關(guān)鍵碼10\n";
else
cout << "沒有發(fā)現(xiàn)關(guān)鍵碼為10的元素\n";
hashdict<char*, char*, CCCompare, CCCompare> Strdict(100, "");
char* str;
Strdict.hashInsert("hello");
if (Strdict.hashSearch("hello", str))
cout << "發(fā)現(xiàn)值 " << str << " 匹配關(guān)鍵碼 hello\n";
else
cout << "沒有發(fā)現(xiàn)關(guān)鍵碼為hello的元素\n";
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -