优先队列入门

7 篇文章 0 订阅
1 篇文章 0 订阅

C++ Priority_Queue(优先队列)

优先队列是一种具有优先级的队列,对常规的队列取值是基于先进先出的顺序,而在优先队列中,选择具有了优先性。
队列:
1.back() 返回一个引用,指向最后一个元素
2.empty() 如果队列空则返回真
3.front() 返回第一个元素
4.pop() 删除第一个元素
5.push() 在末尾加入一个元素
6.size() 返回队列中元素的个数
优先队列:
1.empty() 如果优先队列为空,则返回真
2.pop() 删除第一个元素
3.push() 加入一个元素
4.size() 返回优先队列中拥有的元素的个数
5.top() 返回优先队列中有最高优先级的元素


示例代码如下:

<span style="font-size:18px;">#include<stdio.h>
#include<iostream>
#include<queue>
using namespace std;

int main()
{
    queue<int> que;//队列

    int x[9] = {1,2,1,2,1,2,3,1,3};
    for(int i = 0;i < 9;i++){
        que.push(x[i]);
    }
    for(int i = 0;i < 9;i++){
        printf("%d ",que.front());//结果:1 2 1 2 1 2 3 1 3
        que.pop();
    }
    printf("\n");
    return 0;
}</span>

<span style="font-size:18px;">#include<stdio.h>
#include<iostream>
#include<queue>
using namespace std;

int main()
{
    //priority_queue<int,vector<int>,greater<int> > que;// 从小到大 注意空格用于区分位运算
    //priority_queue<int,vector<int>,less<int> > que;// 从大到小
    priority_queue<int > que; // 默认从大到小

    int x[9] = {1,1,1,2,2,2,3,3,3};
    for(int i = 0;i < 9;i++){
        que.push(x[i]);
    }
    for(int i = 0;i < 9;i++){
        printf("%d ",que.top());//结果:3 3 3 2 2 2 1 1 1
        que.pop();
    }
    printf("\n");
    return 0;
}</span>
对于普通的数据类型的大小排列我们可以直接通过如上的方法定义优先级,但是在我们使用结构体或者需要更为复杂的优先级判断时,就我们需要自己对优先级进行设定。

<span style="font-size:18px;">#include<stdio.h>
#include<iostream>
#include<queue>
using namespace std;

struct Dian{
    int a;
    int b;
    friend bool operator > (Dian x,Dian y){//  ">"代表对从小到大的优先级判断重载
       if(x.a != y.a)
         return x.a > y.a;
       else
         return x.b < y.b;
    }
}dian;

int main()
{
    priority_queue<Dian,vector<Dian>,greater<Dian> > que;// 对应“>”
    //priority_queue<Dian,vector<Dian>,less<Dian> > que;// 对应“<”
    //priority_queue<Dian > que; // 默认从大到小
    int x[9] = {1,1,1,2,2,2,3,3,3};
    int y[9] = {1,2,3,1,2,3,1,2,3};
    for(int i = 0;i < 9;i++){
        dian.a = x[i];
        dian.b = y[i];
        que.push(dian);
    }
    printf("a b\n");
    for(int i = 0;i < 9;i++){
        printf("%d %d\n",que.top().a,que.top().b);
        que.pop();
    }
    printf("\n");
    return 0;
}
/*结果
a b
1 3
1 2
1 1
2 3
2 2
2 1
3 3
3 2
3 1
*/</span>

增添一种新的方法:
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;

struct node
{
    int x;
    bool operator < (const node &a)const
    {
        return a.x < x;//这种比较方法为按从小到大顺序,与a.x<b.x时相反
    }
}a;

int main()
{
    priority_queue<node> que;
    for(int i = 10;i > 0;i--){
        a.x = i;
        que.push(a);
    }
    for(int i = 0;i < 10;i++){
        node k = que.top();
        que.pop();
        printf("%d\n",k.x);
    }

    return 0;
}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值