STL之优先队列

来源:互联网 发布:路易斯威廉姆斯数据 编辑:程序博客网 时间:2024/04/18 10:35

在优先队列中,优先级高的元素先出队列。
标准库默认使用元素类型的<操作符来确定它们之间的优先级关系。

先来看队列的函数

push(x) 将x压入队列的末端
pop() 弹出队列的第一个元素(队顶元素),注意此函数并不返回任何值
front() 返回第一个元素(队顶元素)
back() 返回最后被压入的元素(队尾元素)
empty() 当队列为空时,返回true
size() 返回队列的长度
优先队列的第一种用法,也是最常用的用法:


再是优先队列的函数(其实差不多)


基本操作:

empty() 如果队列为空返回真

pop() 删除对列首元素

push() 加入一个元素

size() 返回优先队列中拥有的元素个数

top() 返回优先队列首元素


priority_queue qi;
通过<操作符可知在整数中元素大的优先级高。
故示例1中输出结果为:9 6 5 3 2

第二种方法:
在示例1中,如果我们要把元素从小到大输出怎么办呢?
可以加一个greater(从小到大输出)改变它的优先级
(less 是从大到小输出)
priority_queue

#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;}
2 0
原创粉丝点击