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

看板C_and_CPP作者 (yeah is you)時間5年前 (2019/04/18 18:17), 5年前編輯推噓4(4013)
留言17則, 8人參與, 5年前最新討論串1/3 (看更多)
開發平台(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): 抱歉,第一次發文,若有什麼不妥或不符合規定請告知,會改進 謝謝各位的幫忙。 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.42.134.69 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1555582666.A.B38.html

04/18 18:39, 5年前 , 1F
在建構時傳進去就好,範例有: http://bit.ly/2VRHqvR fifth
04/18 18:39, 1F

04/18 18:54, 5年前 , 2F
Thank you so much! 等等下班試試
04/18 18:54, 2F
https://i.imgur.com/iP93jph.jpg
有點奇怪,我不覺得有寫的不一樣 ※ 編輯: a29831968 (42.73.37.77), 04/18/2019 22:51:16

04/18 23:28, 5年前 , 3F
當然有不一樣, template 接收的只有 type/non-type
04/18 23:28, 3F

04/18 23:29, 5年前 , 4F
argument, 你給一個 runtime 才能建立的 object 當然
04/18 23:29, 4F

04/18 23:29, 5年前 , 5F
編不過
04/18 23:29, 5F

04/19 03:51, 5年前 , 6F
Ctor的第三個參數傳class的名字 不是method
04/19 03:51, 6F

04/19 07:29, 5年前 , 7F
應該說你不能傳成員函式進去 (因為成員函式有隱藏的 this)
04/19 07:29, 7F

04/19 11:22, 5年前 , 8F
Comparator
04/19 11:22, 8F

04/19 16:09, 5年前 , 9F
std::priority_queue的第三個模板參數是定義小於的
04/19 16:09, 9F

04/19 16:11, 5年前 , 10F
typename 要先生出這個typename的instance才能比較
04/19 16:11, 10F

04/19 16:12, 5年前 , 11F
做法就是把這個typename的ctor的參數作為std::
04/19 16:12, 11F

04/19 16:12, 5年前 , 12F
priority_queue的ctor的參數
04/19 16:12, 12F

04/19 16:16, 5年前 , 13F
以你的例子來說就是 priority_queue<pair<int, int>,
04/19 16:16, 13F

04/19 16:17, 5年前 , 14F
vector<pair<int, int>>, compare> pq(intervals);
04/19 16:17, 14F

04/19 16:24, 5年前 , 15F
抱歉 我查了一下沒有這種用法 看來還是用lambda好了
04/19 16:24, 15F

04/19 16:26, 5年前 , 16F
把上面的pq(intervals)改成pq(compare(intervals))
04/19 16:26, 16F

04/21 19:00, 5年前 , 17F
要傳成員函式請愛用bind
04/21 19:00, 17F
文章代碼(AID): #1Sk4xAiu (C_and_CPP)
文章代碼(AID): #1Sk4xAiu (C_and_CPP)