模板使用自定义类型_priority_queue使用坑点和题集

d8c33bc1d6e9a568e5e4b7bf78c1f0e0.png

2019年7月9日23:27:19 更第一波


priority使用pair比较的坑点

所以用pair的priority_queue只能使用struct的重载比较,why?! 1. 重载运算符的操作不能用于pair类型数据的排序,只能作用于结构体或类对象。---> 所以不能使用node型的priority_queue的函数重载操作符的方法 1. node可以函数操作符重载

f1b4d99a5dc98ce9ff33748d44c7f62d.png

2. pair不支持重载运算符

37900cb72446de95cee1e1f4fa497d13.png
  1. priority_queue定义不支持"嵌入式"函数重载的方法,即 priority_queue, cop>,这样会报错 sort(a,a+n,cop)可以
  2. 比较区只有strut定义

406735fccc5d07e62270c8b41ca70bde.png
  1. 嵌入式函数重载报错

c2cc180f0c489d9d12cdff389fec85c3.png

综上:不能函数重载了,那么就只能struct的自定义重载了咯

ad0d942da9f43e6097995986ecd5a769.png
#include <iostream> // std::cout
#include <queue> // std::priority_queue
using namespace std;

struct node {
    int x, y;
};

bool operator<(const node& a, const node& b)
{
    return a.y > b.y; //less默认大顶堆,改为小顶堆
}
bool cop(const P& a, const P& b) { return a.second > b.second; }

typedef pair<int, int> P;
struct cmp1 {
    // 就是说在cmp里面,当两个P使用  ()的时候,他们使用的下面的函数,也就是创建了一个自定义的函数
    /* 使用时 大概是这样的 cmp1 A, A(a,b) 就类似  非strut的自定义函数了
        bool cmp(P a,P b){ return a.second<b.second;}
     */
    bool operator()(P a, P b){ // 重载() 的函数 叫 仿函数-->紫书找到的
        return a.second > b.second; //小顶堆
    }
};

int main(){
    std::cout << "Popping out elements...";
    // priority_queue<node, vector<node>, less<node>> test;
    priority_queue<P, vector<P>, cmp1> test;
    test.push({ 3, 2 });
    test.push({ 1, 6 });
    test.push({ 2, 8 });
    test.push({ 5, 10 });
    while (!test.empty()) {
        std::cout << ' ' << test.top().second;
        // std::cout << ' ' << test.top().y;
        test.pop();
    }
    cout << endl;
    return 0;
}

题集

注: 为了统一性,所以一般链接地址都是用的Virtual Judge的链接地址,只有VJ上没有的才用其他链接

2019年7月13日第一更

  • poj3190
  • 牛客重现2019矿大省赛G题

附录

priority_queue各种实现方式的时间复杂度对比

dd6cb4b5b83bf879262371b402a4386c.png
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值