C++简单使用priority_queue

priority_queue模板的几个成员函数:
push(T n)将参数n入队列
pop()弹出优先级最高的元素
top()返回优先级最高的元素

#include 
#include 
#include 

using   namespace   std;

class   Person
{
private:
    int age;
    string  name;
public:
    Person(int age,string name):age(age),name(name)
    {

    }
    void    show()
    {
        cout << age << " " << name;
    }
    friend  bool    operator<(const Person &left,const Person &right);
    friend  bool    operator>(const Person &left,const Person &right);
};//定义一个Person类

bool    operator>(const Person &left,const Person &right)//实现这个类的比较运算符
{
    if(left.age>right.age)
        return true;
    else
        return false;
}
bool    operator<(const Person &left,const Person &right)
{
    if(left>right)
        return false;
    else
        return  true;
}
int     main()
{


    priority_queue  q;
    q.push(Person(23,"jack"));
    q.push(Person(13,"baby"));
    q.push(Person(34,"man"));
    q.push(Person(89,"oldman"));
    q.push(Person(1,"birth"));
    //每次出队列都是年龄最大的人,实际内部用的是最大堆
    while(!q.empty())
    {
        Person  t = q.top();
        t.show();
        cout << endl;
        q.pop();
    }//年龄越大,优先级越高
    return 0;
}

C++简单使用priority_queue_第1张图片

你可能感兴趣的:(c++)