[問題] 利用sort排序vector

看板C_and_CPP作者 (大安吳彥祖)時間8年前 (2018/01/17 11:01), 編輯推噓3(3019)
留言22則, 7人參與, 7年前最新討論串1/1
開發平台(Platform): (Ex: Win10, Linux, ...) Win10 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) G++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) #include <vector> #include <algorithm> 問題(Question): 以下程式 建立一個struct comInterval 其中Interval是額外宣告的structure 利用<algorithm>的sort做排序 我比較不明白的是 sort(intervals.begin(),intervals.end(),compInterval()); 送入第三個參數的方法 請問這個方法是運算子多載嗎?? 有沒有正確的術語呢 不知道該從何查起 餵入的資料(Input):預期的正確結果(Expected Output):錯誤結果(Wrong Output):程式碼(Code):(請善用置底文網頁, 記得排版) class Solution { public: struct compInterval { bool operator()(const Interval &a, const Interval &b) const { return a.start<b.start; } }; vector<Interval> merge(vector<Interval> &intervals) { sort(intervals.begin(),intervals.end(),compInterval()); vector<Interval> ret; for(int i=0; i<intervals.size(); i++) { if(ret.empty() || ret.back().end < intervals[i].start) // no overlap ret.push_back(intervals[i]); else // overlap ret.back().end = max(ret.back().end, intervals[i].end); } return ret; } }; 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.163.46.117 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1516158062.A.A42.html

01/17 11:02, 8年前 , 1F

01/17 11:04, 8年前 , 2F
這個網頁我有查到 但我想知道實作這個方法的名字叫做??
01/17 11:04, 2F

01/17 11:07, 8年前 , 3F
第三個參數是比較函數
01/17 11:07, 3F

01/17 11:07, 8年前 , 4F
隨便取,但行為不能違反<的含意
01/17 11:07, 4F

01/17 11:15, 8年前 , 5F
compInterval()是臨時物件,傳入sort內部會以functor
01/17 11:15, 5F

01/17 11:15, 8年前 , 6F
的形式去呼叫
01/17 11:15, 6F

01/17 11:16, 8年前 , 7F
實作邏輯在compInterval::operator()
01/17 11:16, 7F

01/17 11:34, 8年前 , 8F
binary predicate
01/17 11:34, 8F

01/17 15:00, 8年前 , 9F
不知道算不算function pointer?
01/17 15:00, 9F

01/17 15:10, 8年前 , 10F
這例子不算
01/17 15:10, 10F

01/17 15:11, 8年前 , 11F
當然要傳也是可以
01/17 15:11, 11F

01/17 20:20, 8年前 , 12F
這裡的概念是這個參數要能夠當函式名呼叫
01/17 20:20, 12F

01/17 20:21, 8年前 , 13F
能這麼做的物件就稱做 functor, 實際實作是使用 operator()
01/17 20:21, 13F

01/17 20:21, 8年前 , 14F
的運算子重載來定義其行為
01/17 20:21, 14F

01/17 20:22, 8年前 , 15F
那這裡在呼叫時也有一個(), 但這個不是 operator ()
01/17 20:22, 15F

01/17 20:22, 8年前 , 16F
而是單純建立一個物件 (注意 compInterval 是類別名)
01/17 20:22, 16F

01/17 20:23, 8年前 , 17F
這裡的 () 表示建立物件後呼叫其預設建構子
01/17 20:23, 17F

01/18 10:00, 8年前 , 18F
如果很在意inline,比較函數不要傳函數指標
01/18 10:00, 18F

01/18 10:00, 8年前 , 19F
只能傳functor進去
01/18 10:00, 19F

01/19 12:37, 7年前 , 20F
"function objects" by c+g primer 4/e p.530
01/19 12:37, 20F

01/20 03:12, 7年前 , 21F

01/20 03:12, 7年前 , 22F
s/15378055
01/20 03:12, 22F
文章代碼(AID): #1QNhnkf2 (C_and_CPP)