优先队列priority_queue自定义比较函数

以一个例子进行说明,假设优先队列的每个元素是pair<int,int>,我需要自定义一个用于pair<int,int>比较的函数:

decltype返回该变量的类型

bool cmp(pair<int,int>& a, pair<int,int>& b){
    return a.second>b.second;
}

priority_queue<pair<int,int>,vector<pair<int,int>>, decltype(&cmp)> q(cmp);

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
priority_queue自定义比较可以通过重载小于操作符或者自定义函数对象来实现。 通过重载小于操作符,可以定义一个结构体或者类,并在其中重载小于操作符来比较元素的优先级。比如,可以定义一个结构体 MyType,重载小于操作符,使得元素按照 val 从大到小排序。 ``` struct MyType { int val; bool operator<(const MyType& other) const { return val > other.val; // 从大到小排序 } }; priority_queue<MyType> pq; ``` 另一种方法是通过定义函数对象来实现自定义比较。可以创建一个结构体或类,并在其中重载()操作符,然后作为模板参数传递给 priority_queue。比如,可以定义一个类 cmp,重载了()操作符,使得小的元素在队尾,优先级越低。 ``` struct cmp { bool operator()(int a,int b){ return a < b; // 小的放左边,即less } }; priority_queue<int,vector<int>,cmp> pq; ``` 还可以使用函数指针来自定义比较。可以定义一个函数,接受两个参数,并返回一个 bool 值,表示第一个元素是否比第二个元素优先。然后将函数指针作为模板参数传递给 priority_queue。例如,可以定义一个函数对象 cmp,重载了()操作符,使得大的元素在队尾,优先级越低。 ``` bool cmp(int a, int b) { return a > b; // 大的放左边,即greater } priority_queue<int, vector<int>, bool (*)(int, int)> pq(cmp); ``` 以上是三种常见的自定义比较方法,可以根据实际需求选择其中一种来实现自定义比较。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [优先队列自定义比较函数](https://blog.csdn.net/yrk0556/article/details/87994924)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [c++优先队列priority_queue自定义比较函数)](https://blog.csdn.net/qq_21539375/article/details/122128445)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [一文看懂priority_queue自定义比较函数有几种方法](https://blog.csdn.net/weixin_36389889/article/details/129802998)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值