C++ 优先级队列

头文件#include
定义:priority_queue<Type, Container, Functional>
ype 就是数据类型,Container 就是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,默认用的是vector),Functional 就是比较的方式,可以自定义,默认是大顶堆
基本操作:
empty()    如果队列为空,则返回真

pop()    删除对顶元素,删除第一个元素

push()    加入一个元素

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

top()     返回优先队列对顶元素,返回优先队列中有最高优先级的元素

#include <iostream>
#include <functional>
#include <queue>
#include <vector>

using namespace std;

struct cmp1//定义比较结构
{
    bool operator ()(int &x,int &y)
    {
        return x > y;//小顶堆
    }
};

struct cmp2
{
    bool operator ()(int &x,int &y)
    {
        return x < y;//大顶堆
    }
};

struct struct1
{
    int x;

    bool operator < (const struct1 &y) const
    {
        return x > y.x;//小顶堆
    }
};

struct struct2
{
    int x;

    bool operator < (const struct2 &y) const
    {
        return x < y.x;//大顶堆
    }
};

int main()
{
    int a[10] = {2,4,7,9,0,34,546,789,890,234};
    struct1 num1[10];
    struct2 num2[10];
    for (int i=0;i<10;i++)
    {
        num1[i].x = a[i];
        num2[i].x = a[i];
    }
    priority_queue<int>q0;//默认大顶堆
    priority_queue<int,vector<int>,cmp1>q1;//小顶堆
    priority_queue<int,vector<int>,cmp2>q2;//大顶堆
    priority_queue<int,vector<int>,greater<int> >q3;//小顶堆
    priority_queue<int,vector<int>,less<int> >q4;//大顶堆
    priority_queue<struct1>q5; //小顶堆
    priority_queue<struct2>q6;  //大顶堆
    for(int i=0; i<10; i++)
    {
        q0.push(a[i]);
        q1.push(a[i]);
        q2.push(a[i]);
        q3.push(a[i]);
        q4.push(a[i]);
        q5.push(num1[i]);
        q6.push(num2[i]);
    }
    cout<<"q0:"<<endl;
    while(!q0.empty())
    {
        cout<<q0.top()<<" ";
        q0.pop();
    }

    cout<<endl<<"q1:"<<endl;
    while(!q1.empty())
    {
        cout<<q1.top()<<" ";
        q1.pop();
    }
    
    cout<<endl<<"q2:"<<endl;
    while(!q2.empty())
    {
        cout<<q2.top()<<" ";
        q2.pop();
    }

    cout<<endl<<"q3:"<<endl;
    while(!q3.empty())
    {
        cout<<q3.top()<<" ";
        q3.pop();
    }
    
    cout<<endl<<"q4:"<<endl;
    while(!q4.empty())
    {
        cout<<q4.top()<<" ";
        q4.pop();
    }

    cout<<endl<<"q5:"<<endl;
    while(!q5.empty())
    {
        cout<<q5.top().x<<" ";
        q5.pop();
    }
    
    cout<<endl<<"q6:"<<endl;
    while(!q6.empty())
    {
        cout<<q6.top().x<<" ";
        q6.pop();
    }
    return 0;
}

输出

q0:
890 789 546 234 34 9 7 4 2 0
q1:
0 2 4 7 9 34 234 546 789 890
q2:
890 789 546 234 34 9 7 4 2 0
q3:
0 2 4 7 9 34 234 546 789 890
q4:
890 789 546 234 34 9 7 4 2 0
q5:
0 2 4 7 9 34 234 546 789 890
q6:
890 789 546 234 34 9 7 4 2 0

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值