pair作为priority_queue元素时,自定义排序算法

priority_queue介绍

定义:priority_queue<Type, Container, Functional>

Type 就是数据类型。(int ,double等.)

Container 就是容器类型(Container必须是用数组实现的容器,默认vector,但不能用 list。)

默认降序排列,push()队尾插入,pop()弹出头元素。

priority_queue<int> a; //降序排列 等同于priority_queue<int,vector<int>,less<int>> b;
priority_queue<int,vector<int>,greater<int>> c; //升序排列

less表示数字大的优先级越大
greater表示数字小的优先级越大

pair 介绍

pair将两个数据组合成一组数据。
pair的实现是一个结构体,主要的两个成员变量是first、second。

pair<string,string> anon;
pair<string,int> word_count;
pair<string,int> name_age("Tom",18); //初始化
  • 使用make_pair
pair<int,double> p1;
p1 = make_pair(1,1,2);
  • 获取元素
p1.first;
p1.second;
  • pair比较大小

先按first比较,如果相等,再按照second比较。

默认排序

pair作为priority_queue元素时,使用默认less进行降序排列。

#include<iostream>
#include<string>
#include<functional>
#include<queue>
#include<vector>

using namespace std;
typedef pair<int,int> pairint;

int main()
{
        priority_queue<pairint,vector<pairint>,less<pairint> > test;
        pair<int,int> a(5,3);
        pair<int,int> b(1,10);
        pair<int,int> c(5,1);

        test.push(a);
        test.push(b);
        test.push(c);

        while (!test.empty()) {
                cout<<test.top().first<<","<<test.top().second<<endl;
                test.pop();
        }

        return 0;
}                       

输出:

5,3
5,1
1,10

当pair的first值相同时,比较second。

自定义排序顺序

通过自定义function object实现优先队列排序。

#include<iostream>
#include<string>
#include<functional>
#include<queue>
#include<vector>

using namespace std;
typedef pair<int,string> pairint;

class Comp{
        public:
        bool operator()(const pairint &n1,const pairint &n2)const
        {
                if(n1.first == n2.first)
                        return n1.first > n2.first;
                return n1.first > n2.first;
        }
};

int main()
{
        priority_queue<pairint,vector<pairint>,Comp > test;
        pair<int,string> a(5,"a");
        pair<int,string> b(1,"b");
        pair<int,string> c(5,"c");

        test.push(a);
        test.push(b);
        test.push(c);

        while (!test.empty()) {
                cout<<test.top().first<<","<<test.top().second<<endl;
                test.pop();
        }

        return 0;
}

输出:

1,b
5,a
5,c
  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

硬码农二毛哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值