STL--priority_queue--自定义数据类型

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值