优先队列顺序以及自定义顺序的三种方式

本文介绍了C++中的优先队列及其小根堆和大根堆实现,以及如何通过重载operator<、friend函数和function模板来自定义排序顺序。
摘要由CSDN通过智能技术生成

priority_queue<int,vector<int>,greater<int> > q;    //小根堆

priority_queue<int,vector<int>,less<int> > q;      //大根堆,等价于priority_queue<int> q

 大根堆就是把大的元素放在堆顶的堆。小根堆就是把小的元素放在堆顶的堆。

注意,当我们声明的时候碰到两个"<“或者”>"放在一起的时候,一定要记得在中间加一个空格。这样编译器才不会把两个连在一起的符号判断成位运算的左移/右移。

sort自定义的排列顺序与优先队列的相反。运行代码可以更直观感受sort与优先队列的不同

 优先队列自定义顺序的三种方式

#include<bits/stdc++.h>
using namespace std;
struct pp{
	int a;
	int b;
    bool operator< (const pp &b) const{
		return a<b.a;  
	}  //直接重载
};
priority_queue<pp> q;
int main()
{
	pp t[5];
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
	{cin>>t[i].a;q.push(t[i]);}
	sort(t+1,t+1+n);
	for(int i=1;i<=n;i++) cout<<t[i].a<<' ';
	cout<<endl;
	while(!q.empty())
	{
		cout<<q.top().a<<' ';
		q.pop();
		
	}
}
#include<bits/stdc++.h>
using namespace std;
struct pp{
	int a;
	int b;
    friend operator< (pp a,pp b) {
		return a.a<b.a;  
	}//用friend进行自定义
};
priority_queue<pp> q;
int main()
{
	pp t[5];
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
	{cin>>t[i].a;q.push(t[i]);}
	sort(t+1,t+1+n);
	for(int i=1;i<=n;i++) cout<<t[i].a<<' ';
	cout<<endl;
	while(!q.empty())
	{
		cout<<q.top().a<<' ';
		q.pop();
		
	}
}
#include<bits/stdc++.h>
using namespace std;
struct pp{
	int a;
	int b;
};
bool tmp (pp a,pp b) {
	return a.a>b.a;
}
priority_queue<pp,vector<pp>,function<bool(pp,pp)>> q(tmp);//用function自定义顺序

int main()
{
	pp t[5];
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
	{cin>>t[i].a;q.push(t[i]);}
	while(!q.empty())
	{
		cout<<q.top().a<<' ';
		q.pop();
	}
	sort(t+1,t+1+n,tmp);
	cout<<endl;
	for(int i=1;i<=n;i++) cout<<t[i].a<<" ";
}

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
优先队列是一种数据结构,它可以按照一定的优先级顺序来处理元素。在自定义排序时,我们可以使用自定义的比较函数来指定元素的优先级。 在许多编程语言中,优先队列通常使用堆来实现。堆是一种特殊的二叉树,它满足堆属性:对于每个节点i,节点i的值大于(或小于)其子节点的值。 在自定义排序时,我们可以使用比较函数来定义元素之间的优先级。比较函数接受两个元素作为参数,并返回一个整数值,表示它们之间的顺序关系。 下面是一个示例,展示了如何使用Python中的heapq模块来实现自定义排序优先队列: ```python import heapq # 自定义比较函数 def custom_compare(item): return item[0] # 使用元组的第一个元素作为优先级 # 创建一个空的优先队列 priority_queue = [] # 添加元素到优先队列 heapq.heappush(priority_queue, (3, 'A')) heapq.heappush(priority_queue, (1, 'B')) heapq.heappush(priority_queue, (2, 'C')) heapq.heappush(priority_queue, (5, 'D')) # 从优先队列中弹出元素 while priority_queue: item = heapq.heappop(priority_queue) print(item[1]) # 打印元素值 ``` 在上面的示例中,我们定义了一个自定义比较函数`custom_compare`,它使用元组的第一个元素作为优先级。我们使用`heapq.heappush`函数将元素添加到优先队列中,并使用`heapq.heappop`函数从优先队列中弹出元素。最终,我们按照自定义的优先级顺序打印了元素的值。 你可以根据自己的需求定义不同的自定义比较函数来实现不同的排序方式
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值