priority_queue是一个安排好的顺序存储的队列,队首是优先级最高的元素。
Template<class T , class Container = vector<T> , class compare = less<T>>
第一个参数是priority_queue保存的元素类型T,Container是配置的底层容器,priority_queue默认使用了底层容器vector,但也可以使用deque,但是绝对不能使用list,因为list是不能随机访问元素的。Less是一个类模板,支持两个类型为T的元素进行operator<运算,来进行比较。(比较后得到优先级)
优先级越大离队首越近;,通过top()方法可以返回队首元素的const&,
#include <iostream> #include <queue> class Error { public: Error(int priority,std::string errorString) :mPriority(priority),mErrorString(errorString) {} int getPriority(){return mPriority;} std::string getErrorString(){return mErrorString;} friend bool operator <(const Error& lhs , const Error &rhs); friend std::ostream &operator << (std::ostream &os, Error& rhs); private: std::string mErrorString; int mPriority; }; bool operator <(const Error& lhs , const Error &rhs) { return lhs.mPriority < rhs.mPriority; } std::ostream &operator << (std::ostream &os,Error& rhs) { os << rhs.getErrorString() << "priority : " << rhs.getPriority() << std::endl; return os; } class ErrorCorrelateor { public: void addError(const Error & error); Error getError(); private: std::priority_queue<Error> mError; }; void ErrorCorrelateor::addError(const Error & error) { mError.push(error); } Error ErrorCorrelateor::getError() { if(mError.empty()) { throw std::out_of_range("priority queue is empty "); } else { Error tempError = mError.top(); mError.pop(); return tempError; } } int main() { ErrorCorrelateor correlateor; correlateor.addError(Error(1,"Unable to read file")); correlateor.addError(Error(5,"Incorrect entry User")); correlateor.addError(Error(9,"Unable collacate memery")); correlateor.addError(Error(5,"Unable write file")); while(true) { try { Error ec = correlateor.getError(); std::cout << ec ; }catch (const std::out_of_range&) { std::cout << "Finised Error correlatetor" << std::endl; break; } } return 0; }
结果是:
Unable collacate memerypriority : 9
Incorrect entry Userpriority : 5
Unable write filepriority : 5
Unable to read filepriority : 1
Finised Error correlatetor