STL--priority_queue--自定义数据类型
2024-09-05 15:00:05
STL中priority_queue的声明模板有3个参数priority_queue<Type,Container,Functional>。
当使用的数据类型Type为自定义数据类型时有以下3种方法。
1)写仿函数
#include<iostream>
#include<queue>
using namespace std;
struct Node
{
int x,y;
};
struct cmp
{
bool operator()(Node a,Node b)
{
if(a.x!=b.x)
return a.x<b.x;//<为大顶堆,>为小顶堆
return a.y<b.y;
}
};
int main()
{
Node node[]={{,},{,},{,},{,},{,},{,},{,},{,},{,}};
//建立9个结点
priority_queue <Node,vector<Node>,cmp> q(node,node+);//将9个点存入优先队列q
while(!q.empty())//输出
{
Node n=q.top();
cout<<n.x<<' '<<n.y<<endl;
q.pop();
}
return ;
}
2)数据类型外重载operator<
#include<iostream>
#include<queue>
using namespace std;
struct Node
{
int x,y;
};
bool operator<(Node a,Node b)
{
if(a.x!=b.x)
return a.x<b.x;//<为大顶堆,>为小顶堆
return a.y<b.y;
}
int main()
{
Node node[]={{,},{,},{,},{,},{,},{,},{,},{,},{,}};
//建立9个结点
priority_queue <Node> q(node,node+);//将9个点存入优先队列q
while(!q.empty())//输出
{
Node n=q.top();
cout<<n.x<<' '<<n.y<<endl;
q.pop();
}
return ;
}
3)数据类型内重载operator<
#include<iostream>
#include<queue>
using namespace std;
struct Node
{
int x,y;
bool operator<(const Node a)const
{
if(x!=a.x)
return x<a.x;
return y<a.y;
}
};
int main()
{
Node node[]={{,},{,},{,},{,},{,},{,},{,},{,},{,}};
//建立9个结点
priority_queue <Node> q(node,node+);//将9个点存入优先队列q
while(!q.empty())//输出
{
Node n=q.top();
cout<<n.x<<' '<<n.y<<endl;
q.pop();
}
return ;
}
最新文章
- 【MySQL】漫谈MySQL中的事务及其实现
- C#调用C和C++函数的一点区别
- adb 连接时 device offline
- MongoDB 学习笔记(二) 高级查询
- pt-table-checksum 主从复制一致性检查
- 06_init()和destroy()方法
- php文件锁解决少量并发问题
- MYSQL 源代码 学习
- 一些我后写出来的awk脚本
- 加密解密(2)*客户端,服务器,CA(Certificate Authority),公钥,私钥,证书,签名,验证
- ScrollView 嵌套ListView 幻灯冲突,和显示不全
- 国内首家MR头显公司于CES惊艳亮相
- oracle__wm_concat函数
- 使用Nginx+CppCMS构建高效Web应用服务器(之三)
- java+jsp+sql server实现网页版四则运算.
- jacascript 滚动 scroll 与回到顶部
- Selenium WebDriver的工作原理
- Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?
- 2018蓝桥杯 省赛B题(明码)
- [leetcode]22. Generate Parentheses生成括号