首页 > 其他 > 详细

priority_queue详解

时间:2019-02-19 12:09:04      阅读:169      评论:0      收藏:0      [点我收藏+]

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\r\n");
    } 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

 

priority_queue详解

原文:https://www.cnblogs.com/boost/p/10400096.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!