基于堆的优先队列的实现

优先队列的异常处理类

#ifndef PQUEUEEXCEPTION_H_ #define PQUEUEEXCEPTION_H_ #include<stdexcept> #include<string> class PQueueException :public std::logic_error { public: PQueueException(const std::string &message="") :std::logic_error(message.c_str()) {} }; #endif


优先队列类的头文件

#ifndef PRIORITYQUEUE_H_ #define PRIORITYQUEUE_H_ #include"heap_array.h" #include"PQueueexception.h" typedef HeapItemType PQueueItemType; class PriorityQueue { public: PriorityQueue(); //default constructor ,copy constructor and //destrutor are supplied by the complier //priority-queue operations: virtual bool pqempty()const; virtual void pqInsert(const PQueueItemType &newitem) throw(PQueueException); virtual void pqDelete(PQueueItemType &rootitem) throw(PQueueException); private: Heap h; }; #endif


优先队列的实现文件

#include"priorityQueue.h" PriorityQueue::PriorityQueue() :h() {} bool PriorityQueue::pqempty()const { return h.empty(); } void PriorityQueue::pqInsert(const PQueueItemType &newitem) throw(PQueueException) { try{ h.heapInsert(newitem); } catch(HeapException &e) { throw PQueueException("PQueueException : insert item failed !"); } } void PriorityQueue::pqDelete(PQueueItemType &rootitem) throw(PQueueException) { try{ h.heapDelete(rootitem); }catch(PQueueException &e) { throw PQueueException("PQueueException :delete item failed !"); } }


测试优先队列

#include<iostream> #include"priorityQueue.h" using namespace std; int main() { PriorityQueue apq; try{ apq.pqInsert(KeyItem("sort")); apq.pqInsert(KeyItem("exception")); apq.pqInsert(KeyItem("STL")); apq.pqInsert(KeyItem("queue")); apq.pqInsert(KeyItem("priority")); apq.pqInsert(KeyItem("heap")); apq.pqInsert(KeyItem("item")); apq.pqInsert(KeyItem("terrda")); apq.pqInsert(KeyItem("absort")); apq.heapInsert(KeyItem("oppo")); // aheap.display(); KeyItem item; cout<<"the priority queue is :"<<endl; while(!apq.empty()) { apq.pqDelete(item); cout<<item.getKey()<<endl; } }catch(PQueueException &e) { cout<<e.what()<<endl; } return 0; }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值