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]={{0,0},{0,1},{0,2},{1,0},{1,1},{1,2},{2,0},{2,1},{2,2}};
//建立9个结点
priority_queue <Node,vector<Node>,cmp> q(node,node+9);//将9个点存入优先队列q
while(!q.empty())//输出
{
Node n=q.top();
cout<<n.x<<' '<<n.y<<endl;
q.pop();
}
return 0;
}
结果如下,下两种方法都采用大顶堆,结果相同
(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]={{0,0},{0,1},{0,2},{1,0},{1,1},{1,2},{2,0},{2,1},{2,2}};
//建立9个结点
priority_queue <Node> q(node,node+9);//将9个点存入优先队列q
while(!q.empty())//输出
{
Node n=q.top();
cout<<n.x<<' '<<n.y<<endl;
q.pop();
}
return 0;
}
(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]={{0,0},{0,1},{0,2},{1,0},{1,1},{1,2},{2,0},{2,1},{2,2}};
//建立9个结点
priority_queue <Node> q(node,node+9);//将9个点存入优先队列q
while(!q.empty())//输出
{
Node n=q.top();
cout<<n.x<<' '<<n.y<<endl;
q.pop();
}
return 0;
}