开发平台(Platform): (Ex: Win10, Linux, ...)
编译器(Ex: GCC, clang, VC++...)+目标环境(跟开发平台不同的话需列出)
额外使用到的函数库(Library Used): (Ex: OpenGL, ...)
问题(Question):关于PriorityQueue的自定义struct中 opertor overloading 问题
喂入的资料(Input):
预期的正确结果(Expected Output):
错误结果(Wrong Output):Comppiler Error
程式码(Code):(请善用置底文网页, 记得排版,禁止使用图档)
补充说明(Supplement):
版上已经有很多大大们讨论关于 PriorityQueue Compare Function 的解决问题,
我将相关文章整理后再提出问题,以下说明仅凭我个人理解,不精确还请大大们指正。
(1) priority_queue<int,vector<int>> PQ;
默认的 priority_queue 是 max_heap,假若想实现 min_heap 时可以搭配 greater<int>
#include<functional>
priority_queue<int,vector<int>,greater<int>> PQ;
参考这篇( https://pse.is/ECW72 ):overload greater function
bool operator>(const struct_name &one,const struct_name &rhs){
return one.dis>rhs.dis;
}
priority_queue<PAIR,vector<PAIR>,greater<vector<PAIR>::value_type>> PQ;
(2) 自定义 function
struct COMP{
bool operator()(const PAIR &lhs,const PAIR &rhs){ return lhs.dis>rhs.dis; }
};
priority_queue<PAIR,vector<PAIR>,COMP> PQ;
(3) 将定义方式写在 struct 内
struct PAIR{
int id; double dis;
PAIR(int a=0,double b=0):id(a),dis(b){}
// (1) overload operator "less than", but unable to overload "greater than"
bool operator<(const PAIR &rhs)const{ return dis<rhs.dis; }
};
priority_queue<PAIR,vector<PAIR>> PQ;
上述是以ZJ-c942为例,用不同方式宣告使用 PriorityQueue。
附上程式码:https://ideone.com/lYQ8bo
我的问题:为何(3)将定义方式写在 strcut 内的这种方式,
overload operator时 只能是">"不能是"<",虽然说相关的operator都可以从"<"转换
查了一下 StackOverflow,大部分都是谈论解决方法,但没有看到关于上述疑惑的说明
虽然有解决方案即可但还是希望有人可以解答这个无关痛痒的疑惑... 先谢谢大大们