[問題] C++ STL priority_queue

看板C_and_CPP (C/C++)作者 (~"~)時間15年前 (2011/05/13 13:29), 編輯推噓2(2012)
留言14則, 3人參與, 最新討論串1/1
這是在C++ library 看到對STL裡面 priority_queue的敘述 template < class T, class Container = vector<T>, class Compare = less<typename Container::value_type> > class priority_queue; Where the template parameters have the following meanings: T: Type of the elements. Container: Type of the underlying container object used to store and access the elements. Compare: Comparison class: A class such that the expression comp(a,b), where comp is an object of this class and a and b are elements of the container, returns true if a is to be placed earlier than b in a strict weak ordering operation. This can either be a class implementing a function call operator or a pointer to a function. This defaults to less<T>, which returns the same as applying the less-than operator (a<b). The priority_queue object uses this expression when an element is inserted or removed from it (using push or pop, respectively) to grant that the element popped is always the greater in the priority queue. ---------------------- 我想應該是小弟英文不太好 看不懂它到底在說啥= = 綠色那段好像事再說 cmp(a,b) function 裡面 return true 就代表 左邊的要 to be placed earlier then 右邊的 這給我的感覺像是如果我寫一個 Test class 然後在Test 裡面寫下 bool operator() (const Test& a , const Test& b){ if(a.value < b.value) return true; return false; } 的話 priority 的順序應該是從小的value到大的value才對 = = 但是下面又說 operator(a<b) 會是從大到小排列 這樣讓我要記用法以後要寫的時候會有點confused 到底該return 啥 = = 是我英文不好還是怎樣呢??@@ 謝謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.244.131

05/13 13:34, , 1F
priority queue 會從最大的開始 pop
05/13 13:34, 1F

05/13 13:35, , 2F
而所謂"最大"的依據就是根據傳入的 comp
05/13 13:35, 2F

05/13 13:35, , 3F
你不用管它是由小排到大還是由大排到小
05/13 13:35, 3F

05/13 13:36, , 4F
確定 小值 < 大值 的核算結果是 ture 就行
05/13 13:36, 4F

05/13 14:28, , 5F
有 < 就可以實作 >=、>、<=、==、!==, 你只需要知道
05/13 14:28, 5F

05/13 14:29, , 6F
functor是怎麼被使用即可, 不想死背的話可以去研究一
05/13 14:29, 6F

05/13 14:29, , 7F
下原始碼
05/13 14:29, 7F

05/13 21:22, , 8F
謝謝! 所以我要從小的pop 就是 小<大 return false
05/13 21:22, 8F

05/13 21:24, , 9F
所以我還是不太了解 到底return甚麼是左邊的會先被po
05/13 21:24, 9F

05/13 21:24, , 10F
p... 跟qsort 的return 概念好像不太一樣@@@???
05/13 21:24, 10F

05/13 21:24, , 11F
^compare function
05/13 21:24, 11F

05/13 21:31, , 12F
當 comp(a,b) == true 時代表 a 的 priority 比 b 低
05/13 21:31, 12F

05/13 21:32, , 13F
注意 "strict weak ordering"
05/13 21:32, 13F

05/13 21:47, , 14F
!!!! 謝謝 果然是英文不好的原因XD
05/13 21:47, 14F
文章代碼(AID): #1DpC7AiS (C_and_CPP)
文章代碼(AID): #1DpC7AiS (C_and_CPP)