首页 > 其他 > 详细

优先队列的使用方法

时间:2014-08-08 17:54:56      阅读:351      评论:0      收藏:0      [点我收藏+]

模版代码:

bubuko.com,布布扣
#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<<"优先级"<<\t<<""<<endl;
    for(i = 0; i < len; i++)
    {
        cout<<qn.top().priority<<\t<<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;
};

//它表示的含义是这个结构体中有两个值,

 

优先队列的使用方法,布布扣,bubuko.com

优先队列的使用方法

原文:http://www.cnblogs.com/tianxia2s/p/3899716.html

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