priority_queue使用

在c++的STL中priority_queue相当于堆,使用的操作有push(), pop(), top()等;

priority_queue的头文件为<queue>

使用方法及实例:

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

using namespace std;

struct node{
  int idx;
  int key;
  node(int a=0, int b=0):idx(a), key(b){}
};

struct cmp{//使用与struct,当然修改,使之也可以适用于class
  bool operator()(node a, node b){
    return a.key < b.key;
  }
};

template <class T>//自定义模板,实现对基类型如int, float, double等使用
struct my_less{
	bool operator()(T x, T y){
		return x<y;
	}
};


int main(){
  //1. 使用普通int类型测试
  priority_queue<int, vector<int>, my_less<int>> q;
  int i;
  for(i=0;i<10;++i){
    q.push(i);
  }
  q.top()=15;
  cout<<"使用自定义less实现堆:"<<endl;
  while(!q.empty()){
    cout<<q.top()<<"\t";
    q.pop();
  }
  cout<<endl;

  //2. 使用node类型测试
  cout<<"使用node实现:"<<endl;
  priority_queue<node, vector<node>, cmp> p;
  for(i=0;i<10;++i){
    p.push(node(i, i));
  }

  while(!p.empty()){
	  cout<<p.top().key<<"\t";
      p.pop();
  }
  cout<<endl;

  //3. 默认情况下是less,且使用大根堆
  cout<<"使用默认参数实现大根堆:"<<endl;
  priority_queue<int> pp;//相当于priority_queue<int, vector<int>, less<int>> p_big;
  for(int i=0; i<5; i++){
	pp.push(i);
  }
  while(!pp.empty()){
	cout<<pp.top()<<"\t";
	pp.pop();
  }
  cout<<endl;

  //4. 这里使用greater,且使用小根堆
  cout<<"使用生成小根堆:"<<endl;
  priority_queue<int, vector<int>, greater<int>> p_big;
  for(int i=0; i<5; i++){
	  p_big.push(i);
  }
   while(!p_big.empty()){
		cout<<p_big.top()<<"\t";
		p_big.pop();
   }
   cout<<endl<<endl;

  return 0;
}
实验结果:






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值