优先队列的使用方法

模版代码:

#include<iostream>
#include<functional>
#include<queue>
using namespace std;
struct node
{
    friend bool operator< (node n1, node n2)
    {
        return n1.priority < n2.priority;
    }
    int priority;
    int value;
};
int main()
{
    const int len = 5;
    int i;
    int a[len] = {3,5,9,6,2};
    //相对来说这个是很随意的建立了一个数组来保存运算的结果
    //示例1
    priority_queue<int> qi;
    for(i = 0; i < len; i++)
        qi.push(a[i]);                  //这是将所有的元素一个个的向队列里面填充
    for(i = 0; i < len; i++)
    {
        cout<<qi.top()<<" ";
        qi.pop();
    }
    cout<<endl;
 
    //示例2
    priority_queue<int, vector<int>, greater<int> >qi2;
    for(i = 0; i < len; i++)
        qi2.push(a[i]);
    for(i = 0; i < len; i++)
    {
        cout<<qi2.top()<<" ";
        qi2.pop();
    }
    cout<<endl;
    //示例3
    priority_queue<node> qn;
    node b[len];
    b[0].priority = 6; b[0].value = 1;
    b[1].priority = 9; b[1].value = 5;
    b[2].priority = 2; b[2].value = 3;
    b[3].priority = 8; b[3].value = 2;
    b[4].priority = 1; b[4].value = 4;

    for(i = 0; i < len; i++)
        qn.push(b[i]);
    cout<<"优先级"<<'	'<<""<<endl;
    for(i = 0; i < len; i++)
    {
        cout<<qn.top().priority<<'	'<<qn.top().value<<endl;
        qn.pop();
    }

    return 0;
}
View Code

使用个人观点:

在入队时是用到了

priority_queue<int> qi;
for(i = 0; i < len; i++)
qi.push(a[i]);

在出栈的时候则是使用了

for(i = 0; i < len; i++)
{
cout<<qi.top()<<" ";
qi.pop();
}

当然,这个是使用默认的排序方式,顺序是由大到小排列的。那么如果是要将顺序反转过来我们则可以通过写一个结构体来达到自己的目的。

struct node
{
friend bool operator< (node n1, node n2)
{
return n1.priority < n2.priority;
}
int priority;
int value;
};

//它表示的含义是这个结构体中有两个值,其中只是通过priority进行排序的。

 第三种方法解决问题:

priority_queue<node> qn;
node b[len];
b[0].priority = 6; b[0].value = 1;
b[1].priority = 9; b[1].value = 5;
b[2].priority = 2; b[2].value = 3;
b[3].priority = 8; b[3].value = 2;
b[4].priority = 1; b[4].value = 4;

for(i = 0; i < len; i++)
qn.push(b[i]);

我要坚持一年,一年后的成功才是我想要的。
原文地址:https://www.cnblogs.com/tianxia2s/p/3899716.html