一、字典
字典(dictionary)是一些元素的集合。每個元素有乙個稱作key 的域,不同元素的key各
不相同。有關字典的操作有:
• 插入具有給定關鍵字值的元素。
• 在字典中尋找具有給定關鍵字值的元素。
• 刪除具有給定關鍵字值的元素。
隨機訪問:若僅按照乙個字典元素本身的關鍵字來訪問該元素。
順序訪問:指按照關鍵字的遞增順序逐個訪問字典中的元素。順序訪問需借助於begin (用來返回關鍵字最小的元素)和
next (用來返回下乙個元素)等操作來實現。
字典的線性表描述:
增大。為了適應這種描述方式,可以定義兩個類sortedlist和sortedchain。
#ifndef _dict
#define _dict
#includeusing namespace std;
templateclass sortedchain;
template class sortedchainnode
;//e表示鍊錶元素的資料型別, k是鍊錶中排序所用到的關鍵字
templateclass sortedchain
~sortedchain()
bool isempty() const
//int length() const;
bool search(const k& k , e& e) const;
sortedchain& delete(const k& k , e& e);
//sortedchain& insert(const e& e);
sortedchain& distinctinsert(const e& e);
void output(ostream& out) const;
private:
sortedchainnode*first;
};templatebool sortedchain::search(const k& k, e& e) const
return false; // 不存在相匹配的元素
}templatesortedchain& sortedchain::delete(const k& k, e& e)
return *this;
}templatesortedchain& sortedchain::distinctinsert(const e& e)
templatevoid sortedchain::output(ostream& out) const
//過載<<
templateostream& operator<<(ostream& out, const sortedchain& x)
#endif
#include#include"dict.h"
using namespace std;
int main()
bool search(const k& k, e& e) const;
hashtable& insert(const e& e);
void output(ostream& out) const;
private:
int hsearch(const k& k) const;
int d; // 雜湊函式的除數
e *ht; // 雜湊陣列
bool *empty; // 一維陣列
};templatehashtable::hashtable(int divisor)
templateint hashtable::hsearch(const k& k) const
while (j!=i); // 又返回起始桶
return j; // 表已經滿
}templatebool hashtable::search(const k& k, e& e) const
templatehashtable& hashtable::insert(const e& e)
// 不能插入, 檢查是否有重複值或表滿
//if (ht[b] == k) throw badinput(); // 有重複
}templatevoid hashtable::output(ostream& out) const
主函式呼叫:
#include#include"dict.h"
using namespace std;
int main()
=6/7。因此b最小為(7n/6)=1167.b=d=37*37 =1369,應為乙個比較好的值(雖然不是最小的選擇)。
複製搜尋 複製
搜尋
字典 與雜湊表 雜湊
python 用雜湊表來實現 dict。雜湊表其實是乙個稀疏陣列 總是有空白元素的陣列稱為稀疏陣列 在一般書中,雜湊表裡的單元通常叫做表元 bucket 在 dict 的雜湊表當中,每個鍵值對都占用乙個表元,每個表元都有兩個部分,乙個是對鍵的引用,乙個是對值的引用。因為每個表元的大小一致,所以可以通...
字典和雜湊表
在字典 或對映 中,用 鍵 值 對的形式來儲存資料。如果item變數是乙個物件的話,需要實現tostring方法,否則會導致出現異常的輸出結果,如 object object function defaulttostring item else if item undefined else if t...
字典雜湊表的實現原理 字典雜湊表的實現原理
兩個陣列 bucket陣列 儲存key的hash桶,桶指的是把hashcode分配到一定的範圍內 entry陣列 用來儲存實現的值,它是乙個單向鍊錶,bucket總是儲存鍊錶的最後乙個元素 實現方式 通過雜湊桶來實現的k v儲存,通過key的hash碼,再進行桶計算,生成乙個在某個範圍內的值,這就是...