priority_queue 自定义类型重载运算符
时间: 2023-08-26 20:18:12 浏览: 103
容器适配器-ucos-iii 英文手册 for stm32
在priority_queue中对自定义类型进行排序时,可以通过重载运算符来定义比较规则。比如,如果要按照元素值从大到小排序(小顶堆),可以在自定义类型的结构体或类中重载小于运算符(operator<)。例如,定义一个名为MyType的结构体,其中包含一个名为val的整数成员变量,可以重载小于运算符如下:
struct MyType {
int val;
bool operator<(const MyType& other) const {
return val > other.val; // 从大到小排序
}
};
然后可以使用以上自定义类型来定义一个priority_queue实例:
priority_queue<MyType> pq;
这样,当向priority_queue中插入元素时,会按照自定义的比较规则进行排序。在上述例子中,元素会按照val的值从大到小排序。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [关于struct自定义类型的set/priority_queue重载运算符](https://blog.csdn.net/weixin_59534651/article/details/123141614)[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^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [一文看懂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^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [C++ sort / priority_queue自定义比较](https://blog.csdn.net/ahundredmile/article/details/126025258)[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^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文