開發平台(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,大部分都是談論解決方法,但沒有看到關於上述疑惑的說明
雖然有解決方案即可但還是希望有人可以解答這個無關痛癢的疑惑... 先謝謝大大們
作者:
LPH66 (-6.2598534e+18f)
2019-06-13 07:48:00deque 相對 vector 的一個優點是容器增大時不需複製/移動到新的空間, 光這一點就很有理由在一些狀況下用 deque 了嘛, 如果你真的對 comparator 在第三格感到很困擾的話C++17 的 deduction guide 可以由建構子參數型態去推模版然後 priority_queue 的建構子 comparator 都排在容器前面