STL 优先级队列

STL中优先级队列的模版声明中有三个参数,priority_queue<Type,Container,Functional>,故名思义,Type为数据类型,Container则是必须用数组实现的容器,常见的vector,deque,但不能用List,STL默认的是vector,后面的Functional为比较方式,默认的基本类型为数值大的优先。即首元素是最大值。

那么在解决问题时,有时会用到最小堆,即优先级队列中首元素为最小的元素,对于基本类型,可用STL的仿函数直接拿来用

    priority_queue<Type,vector<Type>,greater<Type> > Q;

  Type即为基本类型,int,long long,double之类的。

对于结构体呢,我们就需要自定义函数了,类似于qsort中自定义cmp函数。经典题型可参考NYOJ 55

自定义函数既可以重载operator< 函数 也可以自定义函数名。

例子1:重载operator< 实现按x从小到大排序,若x相同,则按照y的大小排序

#include<iostream>
#include<stdio.h>
#include<queue>
using namespace std;
struct Point
{
 int x,y;
};
bool operator<(Point a,Point b)
{
 if(a.x==b.x) return a.y>b.y;
 return a.x>b.x;
}
int main()
{
    priority_queue <Point> Q;            //只需要带一个参数
    Point temp;
    for(int i=0;i<5;++i)              //输入5个数
    {
  cin>>temp.x>>temp.y;
  Q.push(temp);
 }
 cout<<"*******************"<<endl;
    while(!Q.empty())
    {
  cout<<Q.top().x<<" "<<Q.top().y<<endl;
  Q.pop();
 }
 system("pause");
 return 0;
}

另外一种,可带三个参数,例子如下

#include<iostream>
#include<stdio.h>
#include<queue>
using namespace std;
struct Point
{
 int x,y;
};
struct cmp          //仿函数
{
bool operator()(Point a,Point b)        //这里不是重载了,< 变成()了
{
 if(a.x==b.x) return a.y>b.y;
 return a.x>b.x;
}
};
int main()
{
    priority_queue <Point,vector<Point>,cmp> Q;   //三个参数
    Point temp;
    for(int i=0;i<5;++i)
    {
  cin>>temp.x>>temp.y;
  Q.push(temp);
 }
 cout<<"*******************"<<endl;
    while(!Q.empty())
    {
  cout<<Q.top().x<<" "<<Q.top().y<<endl;
  Q.pop();
 }
 system("pause");
 return 0;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值