优先队列的异常处理类
#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; }