c++ 优先级队列priority_queue的使用

c++ priority_queue是对其他容器元素顺序的调整包装; 堆的原理

1.定义

priority_queue<Type, Container, Functional> q;

其中,Type是数据类型,Container是低层容器,如vector, stack, deque等. Functional是比较函数;默认可以使用greater(从小到大), less(从大到小)排序。例如,定义一个元素为整数的小顶堆:

priority_queue<int, vector<int>, greater<int>> q;

2.头文件
#include<queue>


3.常用接口
push  添加一个元素到队尾,并自动调整堆
pop    弹出队头元素
top   获取队头元素
empty 堆是否为空
size   堆的大小

4.基本数据类型 使用
原始数据[1,2,3,4,5,6,7,8] 
priority_queue<int> q;            //默认是大顶堆
等价于priority_queue<int,vector<int>, less<int>> q; 

堆内部的数据[8,7,6,5,4,3,2,1]

小顶堆的构造
priority_queue<int,vector<int>, greater<int>> q2;
堆内部的数据[1,2,3,4,5,6,7,8]

5.关联类型,pair
priority_queue<pair<int,int>> q3
排序规则默认先比较第一个值,后比较第二个值
pair<int,int> a(1,2)
pair<int,int> b(2,3)
pair<int,int> c(3,4)
q3.push(a);
q3.push(b);
q3.push(c);
q3.top().first, q3.top().second

6.自定义类型,需要重载<运算符
struct tmp1{
    int x;
    tmp1(int a) {x = a;}
    operator <(const tmp1 &a) const {
        return x < a.x;
    }
};

tmp1 t1(3);
tmp1 t2(4);
tmp1 t3(5);

priority_queue<tmp1> q;
//插入元素 
q.push(t1);
q.push(t2);
q.push(t3);

//访问
q.top().x 

#include<iostream> 
#include<vector>
#include<queue>
using namespace std;
typedef pair<int,int> P;

//自定义类型
struct tmp1 //运算符重载<
{
    int x;
    tmp1(int a) {x = a;}
    bool operator<(const tmp1& a) const
    {
        return x < a.x; //大顶堆
    }
};

struct tmp2 //重写仿函数,用于比较元素
{
    bool operator() (const pair<int,int> &a, const pair<int,int> &b) 
    {
   		if (a.first < b.first) {
   			return true;
		}
		return a.second < b.second;
    }
};

int main() {
	
	//1.升序队列 , 小顶堆 
	priority_queue<int,vector<int>,greater<int>> q1; 
	
	//2.降序队列, 大顶堆 
	priority_queue<int,vector<int>,less<int>> q2; 
	for (int i = 0; i < 10; i++) {
		q1.push(i);
		q2.push(i); 
	} 
	
	while (!q1.empty()) {
		cout << q1.top() << " ";
		q1.pop();
	}
	cout << endl;
	
	while (!q2.empty()) {
		cout << q2.top() << " ";
		q2.pop();
	}
	cout << endl;
	
	//3.关联容器
	priority_queue<P> q3;
	P p1(1,1);
	P p2(1,2);
	P p3(1,3);
	q3.push(p1);
	q3.push(p2);
	q3.push(p3);
	while (!q3.empty()) {
		cout << q3.top().first << " - " << q3.top().second << endl;
		q3.pop();
	}
	//3.1 等价于
	priority_queue<P,vector<P>,tmp2> q4;
	q4.push(p1);
	q4.push(p2);
	q4.push(p3);
	while (!q4.empty()) {
		cout << q4.top().first << " = " << q4.top().second << endl;
		q4.pop();
	}
	
	//4.自定义类型 
	priority_queue<tmp1> d;
	tmp1 a(3);
	tmp1 b(4);
	tmp1 c(5);
	d.push(a);
	d.push(b);
	d.push(c);
	
	while (!d.empty()) {
		cout << d.top().x << " ";
		d.pop();
	}
	cout << endl;
	return 0;
}

参考:c++优先队列(priority_queue)用法详解_吕白_的博客-CSDN博客_c++ 优先队列 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值