字典是由一些形如(k,v)的数对所组成的集合,其中k是关键字,v是与关键字k对应的值。任意两个数对,其关键字都不等。字典的关键字是有序的。可以仅按照字典元素本身的关键字来访问元素,即随机访问;也可以按照关键字递增的顺序来依次访问字典中的元素,即顺序访问。
多重字典,允许两个或更多的数对可以具有相同的关键字。
template<class K, class E>
class dictionary
{
public:
virtual ~dictionary() {}
virtual bool empty() const = 0;
// return true iff dictionary is empty
virtual int size() const = 0;
// return number of pairs in dictionary
virtual pair<const K, E>* find(const K&) const = 0;
// return pointer to matching pair
virtual void erase(const K&) = 0;
// remove matching pair
virtual void insert(const pair<const K, E>&) = 0;
// insert a (key, value) pair into the dictionary
};
template<class K,class E>
struct pairNode{
pair<K,E> element;
pairNode* next;
pairNode() {}
pairNode(pair<K,E>& newElement)
{
element=newElement;
next=NULL;
}
pairNode(pair<K,E>& newElement,pairNode* node)
{
element=newElement;
next=node;
}
}
这里采用线性表来实现字典
template<class K, class E>
class SortedNode : public dictionary {
public:
SortedNode(){
firstNode=NULL;
size=0;
}
~SortedNode(){
while(firstNode)
{
pairNode* node=firstNode->next;
delete firstNode;
firstNode=node;
}
}
pair<const K, E>* find(const K& k) const
{
pairNode* p=firstNode;
while(p&&p->element.first<k)
{
p=p->next;
}
if(p!=NULL&&p->element.first==k)
return &p->element;
return NULL;
}
void insert(const pair<const K, E>& thepair){
pairNode* p=firstNode;
pairNode* tp=NULL;//用来指向要插入位置的前一个节点
while(p&&p->element.first<thepair.first)
{
tp=p;
p=p->next;
}
//字典中存在关键字等于thepair关键字的节点
if(p!=NULL&&p->element.first==thepair.first)
{
p->element.second=thepair.second;
}
//字典中不存在关键字等于thepair关键字的节点
else{
pairNode* node=new pairNode(thepair);
//字典不为空,字典的元素的关键字都大于thepair的关键字
if(tp==NULL&&p!=NULL){
node->next=firstNode;
firstNode=node;
}
//字典为空
else if(tp=NULL&&p==NULL)
firstNode=node;
//字典不为空,元素的关键字都小于thepair的关键字
else tp->next=node;
size++;
}
}
void erase(const K& k){
pairNode* p=firstNode;
pairNode* tp=NULL;//用来指向要插入位置的前一个节点
while(p&&p->element.first<k)
{
tp=p;
p=p->next;
}
if(p!=NULL&&p->element.first==k)
{
if(tp==NULL) firstNode=p->next;
else tp->next=p->next;
delete p;
size--;
}
}
private:
pairNode* firstNode;
int size;
}