admin管理员组文章数量:1623803
优先队列--自定义排序
- A: 默认排序
- B: 自定义排序
- 方法一: 运算符重载
- 方法二: 重写仿函数
A: 默认排序
1,priority_queue< int > a; // 基础类型, 默认是大顶堆,自动排
2,priority_queue<int, vector< int >, greater< int > > c; //基础类型,变小根堆
#include<bits/stdc++.h>
#define ll long long
#define PP pair<int,int>
using namespace std;
int main()
{
priority_queue< int,vector<int>,greater<int> > q;
q.push(1);
q.push(5);
q.push(3);
while(!q.empty())
{
printf("%d\n",q.top());
q.pop();
}
return 0;
}
B: 自定义排序
方法一: 运算符重载
结构体内 重载运算符<
#include<bits/stdc++.h>
#define ll long long
using namespace std;
#define PP pair<int,int>
struct Node{
int x,y,z;
Node(int a,int b,int c)
{
x=a,y=b,z=c;
}
bool operator<(const Node &a) const //***** 运算符重载 < ,内置
{
return a.z>z; //按z值降序
}
};
int main()
{
priority_queue<Node> q;
q.push(Node(1,2,3));
q.push(Node(3,9,1));
q.push(Node(2,3,4));
while(!q.empty())
{
printf("%d %d %d\n",q.top().x,q.top().y,q.top().z);
q.pop();
}
return 0;
}
方法二: 重写仿函数
priority_queue< 类型,vector< 类型 >,cmp> q;
#include<bits/stdc++.h>
#define ll long long
using namespace std;
#define PP pair<int,int>
struct cmp{
//重写仿函数
bool operator()(PP a,PP b)
{
return a.first>b.first;
}
};
int main()
{
priority_queue<PP,vector<PP>,cmp> q;
q.push(make_pair(4,6));
q.push(make_pair(9,4));
q.push(make_pair(6,1));
while(!q.empty())
{
printf("%d %d\n",q.top().first,q.top().second);
q.pop();
}
return 0;
}
本文标签: 队列自定义priorityqueue
版权声明:本文标题:优先队列(priority_queue)--自定义排序 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1728895881a1178399.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论