优先队列基本用法

priority_queue在头文件#include<queue中,他能自定义优先级,优先级高的先出队,基本操作和queue差不多,就是priority_queue自带排序,排序可自定义

top 访问队头元素
empty 队列是否为空
size 返回队列内元素个数
push 插入元素到队尾 (并排序)
emplace 原地构造一个元素并插入队列
pop 弹出队头元素
swap 交换内容

定义:priority_queue<Type, Container, Functional>
Type 就是数据类型,Container 就是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector),Functional 就是比较的方式,当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大顶堆。
不多说,基本就下面代码的手法,其他的我也不会(我太菜了)

#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <cstring>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <vector>
#include <ctype.h>
using namespace std;
typedef long long ll;
const ll mod=1e9+7;
const int inf=0x3f3f3f3f;
#define mem(a,b) memset(a,b,sizeof(a))
#define IOS ios::sync_with_stdio(false);cin.tie(0)
#define mcy(a,b) memcpy(a,b,sizeof(a))
priority_queue<int,vector<int>,greater<int> >a;//升序排列
priority_queue<int,vector<int>,less<int> >b;//降序排列
priority_queue<string,vector<string>,greater<string> >c;
priority_queue<string,vector<string>,less<string> >d;
struct node {
    int x;
}aa[1005];
struct cmp
{
    bool operator() (node m,node n)
    {
        return m.x<n.x;
    }
};
int main()
{
    for(int i=1;i<=9;++i)
    {
        a.push(i);
        b.push(i);
    }
    while (!a.empty())
    {
        cout << a.top() << ' ';
        a.pop();
    }
    cout << endl;
    while (!b.empty())
    {
        cout << b.top() << ' ';
        b.pop();
    }
    cout << endl;
    string x,y,z;
    x="aaab";
    y="aabc";
    z="abc";
    c.push(x),c.push(y),c.push(z);
    d.push(x),d.push(y),d.push(z);
    while (!c.empty())
    {
        cout << c.top() << ' ';
        c.pop();
    }
    cout << endl;
    while (!d.empty())
    {
        cout << d.top() << ' ';
        d.pop();
    }
    cout << endl;
    //结构体类型
    priority_queue<node,vector<node>,cmp>ss;
    for(int i=1;i<=5;++i)
    {
        aa[i].x=rand();
        ss.push(aa[i]);
    }
    while (!ss.empty())
    {
        cout << ss.top().x << ' ';
        ss.pop();
    }
    cout << endl;
}
输出:
1 2 3 4 5 6 7 8 9 
9 8 7 6 5 4 3 2 1 
aaab aabc abc 
abc aabc aaab 
1622650073 1144108930 984943658 282475249 16807 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值