C++ STL 优先队列详解

一.解释:

  优先队列是队列的一种,不过它可以按照自定义的一种方式(数据的优先级)来对队列中的数据进行动态的排序,每次的push和pop操作,队列都会动态的调整,以达到我们预期的方式来存储。

  例如,将元素5 3 2 4 6依次push到优先队列中,规定顺序为从大到小并输出,输出顺序为6 5 4 3 2 

二.用法

  1.头文件

#include<queue>//与队列相同,不必引入vector的头文件

  2.定义方式

priority_queue<int> p;//最大值优先,是大顶堆一种简写方式
priority_queue<int,vector<int>,greater<int>>q1;//最小值优先,小顶堆
priority_queue<int,vector<int>,less<int> >q2;//最大值优先,大顶堆

//其中第一个参数是数据类型,第二个参数为容器类型。第三个参数为比较函数。

    在使用时,我们会有很多时间用到根据结构体的某一个元素进行排序,下面给出定义结构体的优先级比较方式

struct node
{
    string name;
    int price;
    friend bool operator< (node a, node b)
    {
        return a.price < b.price; // 相当于less,这是大顶堆,反之则是小顶堆,最大值优先
    }
} stu; //定义结构体变量

这样直接可以:
priority_queue<node > q;

    可以将比较运算符外置,方法如下

struct node
{
    string name;
    int price;
} stu; //定义结构体变量

struct cmp
{
    bool operator () (node a, node b) // 重载括号
    {
        return node.price < node.price; // 相当于less,大顶堆
    }
};

  3.常用操作:

q.push(x) //将x加入队列中,即入队操作

q.pop() //出队操作(删除队列首元素),只是出队,没有返回值

q.top() //返回第一个元素(队首元素)优先队列的队首用top,而普通队列的队首用front

q.size() //返回栈队列中的元素个数

q.empty() //当队列为空时,返回 true

三.举例

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
#include <vector>
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;
}
原文地址:https://www.cnblogs.com/aiguona/p/7200718.html