优先队列

1定义优先队列

#include<stdio.h>
#include<queue>
using namespace std;
int main()
{
    priority_queue<int>q;
}

2优先队列的使用

#include<stdio.h>
#include<queue>
using namespace std;
int main()
{
    priority_queue<int>q;
    q.push(1);
    q.push(10);
    q.push(5);       //进队列
    int t;
    while(!q.empty())//判断是否为队列为空
    {
     t=q.top();      //取出队首的值
     printf("%d ",t);
     q.pop();       //出队列
    }
    printf("\n");
    return 0;
}

q.push( )  进队列

q.pop()出队列

q.top( ) 取队首值

q.empty( )  判断队列是否为空,为空返回真,否则返回假;

3队列优先级的定义

优先队列默认是从小到大,要改变的话需要重新定义优先级;

1 结构体中可以用重载符  "<" 来定义优先级

  1. #include<stdio.h>
  2. #include<queue>
  3. using namespace std;
  4. struct note
  5. {
  6.  int x,y;
  7.  bool operator < (const note &a) const //重载 "<"操作符,指定优先规则
  8.  {
  9.      return a.x<x;//按X从小到大排序
  10.      return a.x>x;//从大到小
  11.  }
  12. };
  13. int main()
  14. {
  15.     priority_queue<note>q;
  16.     
  17.     return 0;
  18. }

 2

非结构体,结构体也能用重载操作符 "( )"

  1. #include<stdio.h>
    #include<vector>
    #include<iostream>
    #include<queue>
    using namespace std;
    struct cmp
    {

     bool operator () (const int &a,const int &b) //重载 "<"操作符,指定优先规则
     {
         return a>b;//从小到大排序
         return a<b;//从大到小
     }
    };
    int main()
    {
        priority_queue<int,vector<int>,cmp>q; //重载定义优先队列
        return 0;
    }
     

 

2 另一种方法

priority_queue <int,vector<int>,less<int> > q;从大到小

priority_queue <int,vector<int>,greater<int> > q;从小到大

具体用见代码:

  1. #include<stdio.h>
  2. #include<vector>
  3. #include<iostream>
  4. #include<queue>
  5. using namespace std;
  6. int main()
  7. {    priority_queue <int,vector<int>,less<int> > q;
  8.     q.push(1);
  9.     q.push(10);
  10.     q.push(5);
  11.     int t;
  12.     while(!q.empty())
  13.     {
  14.         t=q.top();
  15.         printf("%d ",t);
  16.         q.pop();
  17.     }
  18.     printf("\n");
  19.     return 0;
  20. }

输出为 10 5 1; 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值