Re: [問題] C++ 如何修改compare

作者: poyenc (髮箍)   2019-04-19 22:03:02
※ 引述《a29831968 (yeah is you)》之銘言:
: 開發平台(Platform): (Ex: Win10, Linux, ...)
: 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
: 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
: 問題(Question):
: 餵入的資料(Input):
: 預期的正確結果(Expected Output):
: 錯誤結果(Wrong Output):
: 程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
: 不好意思,我是在刷題的時候遇到問題
: 可能關鍵字下錯所以一直找不太到答案,所以想在這裡求助大神
: 一般來說
: 定義 priority_queue<>時,第三個參數放的是compare
: 在刷題時,模板是這樣子
: class solution{
: // 裡面會有題目自訂的funciton
: // 若是我在題目內宣告priority_queue,且要用到符合需求的compare時,
: // 我會在該class外面自行定義
: vector<int> mergeTwoSortedArray(vector<int> a, vector<int> b) {
: // 隨便假設
: priority_queue<int, vector<int>, compare> pq;
: }
: };
: // ex
: class compare{
: bool operator()(const int &a, const int &b) {
: return a > b;
: }
: };
: 可是我現在需要在class solution題目給的function內去更改compare,
: 因為我需要使用到題目給的input,不單單只是整數,說不定要用到a的size之類的(假設)
: 補充說明(Supplement):
: 抱歉,第一次發文,若有什麼不妥或不符合規定請告知,會改進
: 謝謝各位的幫忙。
除了語法問題, 小弟來補充一下你可能不知道的二三事, 通常
STL algorithms/containers 使用你給的 function objects 時都
會有以下常見的需求:
1. consistent behavior
2. copy constructible
3. stateless
4. callable by given arguments
第一點很合理, 假如我現在寫了自己的 less 比較兩個整數, 前 10
次呼叫 less{}(1, 2) 會回傳 true, 但第 11 次開始回傳 false,
想當然拿來當排序準則是會失敗的:
https://bit.ly/2VbG9m2
第二點在該 algorithm/container 使用期間, 你給的 function
object 必須一直存活著, 所以通常介面會用 const T& 來接你給的
物件引數, 而它們會複製一份在內部使用, 這個通常在規格書或
cppreference 找得到:
http://eel.is/c++draft/priority.queue#priqueue.cons
第三點比較像是前兩點的綜合, 因為會複製資料成員(複製狀態),
在 algorithms/containers 內部使用時可能行為就變掉不如預期
第四點要先知道給的物件會被怎樣使用, 不然會得到一大坨編譯錯
誤不知道該怎麼辦, 也是文件就找得到:
https://bit.ly/2GmpPpf
因為 std::priority_queue 類別模版接的都是型別引數, 所以你
需要在編譯的時候想辦法推導出來. 就我所知有兩種方法給你參考:
其中一種是自訂型別, 提供多載 operator(); 另一種是先用
lambda expression 建立 closure, 再透過 decltype() 得到它的
型別, 當作引數傳給 std::priority_queue 類別模版
方法一 https://bit.ly/2vcOIOV
方法二 https://bit.ly/2L4ucen
happy coding!
作者: heardringo (love ringo)   2019-04-19 23:26:00
作者: TitanEric (泰坦)   2019-04-20 00:12:00
優文
作者: ggBird (ggBird)   2019-04-20 06:45:00
作者: bigbite (子子孫孫永保用)   2019-04-20 10:17:00
優文
作者: aa0917954358 (Doem)   2019-04-20 22:36:00
可以請教一下 overloading operator()跟operator<當作compare function的概念差在哪裡嗎?

Links booklink

Contact Us: admin [ a t ] ucptt.com