Re: [問題] PriorityQueue 的 operator overload問題

看板C_and_CPP (C/C++)作者 (髮箍)時間6年前 (2019/06/13 01:37), 6年前編輯推噓1(100)
留言1則, 1人參與, 6年前最新討論串2/2 (看更多)
※ 引述《fatcat8127 (胖胖貓)》之銘言: : 版上已經有很多大大們討論關於 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,大部分都是談論解決方法,但沒有看到關於上述疑惑的說明 : 雖然有解決方案即可但還是希望有人可以解答這個無關痛癢的疑惑... 先謝謝大大們 簡單說結論: 非不得已不要重載 operator<() 重載運算子應該被視為最後的解決方案, 為什麼呢? 因為除了 assignment operator 以外, 其餘的運算子都可以在類別本體以外 作宣告, 亦即: 即使不是類別作者也可以隨意重載運算子. 如果你 確定想這麼做, 以宣告的位置來分, 有 4 種情境需要注意: namespace n1 { struct meow { (1) bool operator<(const meow&) const; }; (2) bool operator<(const meow&, const meow&); } (3) bool operator<(const n1::meow&, const n1::meow&); namespace n2 { (4) bool operator<(const n1::meow&, const n1::meow&); } 先不說無法明確表達語意這件事; 光是讓呼叫能正常編譯就困難重 重 (想想看為什麼). 不過也因為這樣高度的客製化彈性, 我們甚至 可以選擇性地讓編譯器呼叫想要的運算子實作: https://wandbox.org/permlink/mXhfObcCglfDxPdY 標準函式庫裡類似的例子有命名空間 std::rel_ops 和 std::string_literals. 把握 overload resolution 規則, 可以作 到改變 std::less<T> 的行為: https://wandbox.org/permlink/0Fd5SrhjOPQ2LztO 因此開發/使用這類 function object 時有幾點注意事項: 開發者 1. 不要依賴運算子造成語意不明, 用 Argument-dependent lookup (ADL) 來找到類別作者所設計, 或者覺得合適的 函式呼叫 2. 如果非要依賴某些運算子, 儘量減少種類和參數組合 使用者 1. 不要假設底層的實作為何 2. 即使已經知道底層實作, 確保想要的函式有在編譯器呼 叫候選名單裡 最後還是建議原po自己寫個類別作比較啦 -- P1389R0: Guidelines for Teaching C++ to Beginners https://bit.ly/2GvDWKb SG20 Education and Recommended Videos for Teaching C++ https://www.cjdb.com.au/sg20-and-videos -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.193.76.216 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1560361067.A.C9B.html ※ 編輯: poyenc (123.193.76.216 臺灣), 06/13/2019 01:45:02

06/14 18:50, 6年前 , 1F
感謝大神的解釋
06/14 18:50, 1F
文章代碼(AID): #1T0JXhoR (C_and_CPP)
文章代碼(AID): #1T0JXhoR (C_and_CPP)