C++队列与优先队列

使用标准库头文件

#include<queue>

队列常用的函数

  q.push(x);  向优队列添加一个元素

  q.pop();     删除队列头元素

  q.front(); 返回队列头元素

  q.size();   返回队列元素个数

  q.empty(); 如果优先队列为空,返回真

  q.back(); 返回队列尾部首元素

  优先队列常用的函数

  q.push(x); 向优先队列添加一个元素

   q.pop(); 删除优先队列优先级最高的元素

  q.top(); 返回优先队列优先级最高的元素

  q.size(); 返回优先队列元素个数

  q.empty(); 如果优先队列为空,返回真

  接下来主要讲优先队列的使用:

  1、

  #include<iostream>
#include<cstdio>
#include<stack>
#include<queue>
using namespace std;
int main()
{
    priority_queue<int> q;
    q.push(3);
    q.push(11);
    q.push(0);
    q.push(7);
    q.push(-1);
    q.push(15);
    while(!q.empty())
    {
        cout << q.top() << " ";
        q.pop();
    }
    cout << endl;
    return 0;
}

 结果为 15 11 7 3 0 -1

 如果我想让该优先队列输出小到大如何实现呢?很简单,只要将priority_queue<int> q 改成 priority_queue<int,vector<int>,greater<int>> q; 原因在于没个参数表示的含义在于:第一个表示数据类型;第二个表示保存该数据类型的容器(默认情况为vector);第三个表示自定义的优先规则(默认情况下,元素大的优先级高)。greater表示数据优先级顺序是从小到大,另外greater也可以改成less,表示数据优先级顺序是从大到小。

2、

#include<iostream>
#include<cstdio>
#include<stack>
#include<queue>
using namespace std;
int main()
{
    priority_queue<int,vector<int>,greater<int> > q;
    q.push(3);
    q.push(11);
    q.push(0);
    q.push(7);
    q.push(-1);
    q.push(15);
    int len=q.size();
    for(int i=0;i<len;i++)
    {
        cout << q.top() << " ";
        q.pop();
    }
    cout << endl;
    return 0;
}

结果为:-1 0 3 7 11 15



3、
如果想自定义优先级并且数据类型不是基本数据类型,而是复杂数据类型,则必须重载其中的operator();
#include<iostream>
#include<cstdio>
#include<stack>
#include<queue>
using namespace std;
struct node
{
    int a;
    int b;
    bool operator < (const node &t) const{
       return b<t.b;
    }
};
int main()
{
    priority_queue<node> q;
    node pp;
    for(int i=0;i<3;i++)
    {
        scanf("%d %d",&pp.a,&pp.b);
        q.push(pp);
    }
    while(!q.empty())
    {
        pp=q.top();
        q.pop();
        cout << pp.a << " " << pp.b << endl;
    }
    return 0;
}

输入
3 3
1 5
7 0

输出
1 5
3 3
7 0



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值