※ 引述《LRM (小烏龜)》之銘言:
: boost library先放著,以後有空再去熟悉>"<
: 我的寫法:
: struct TestArg3 {
: bool operator()(MyClass * c1, MyClass * c2){
: return a->x < b->x;
: }
: };
: 傳入priority_queue,如下:
: priority_queue<MyClass*, vector<MyClass*>, TestArg3 > test;
: 就ok了
: 程式功力不夠厚,老實說對template還不是太熟悉…
: 參考less的原始碼,
: struct less : public binary_function<_Ty,_Ty,bool>
: 拿掉後面的繼承好像也沒事
這是因為你沒有使用繼承下來的 typdef
binary_function 的定義 (VS2008)
template<class Arg1, class Arg2, class Result>
struct binary_function {
typedef Arg1 first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
};
如果要搭配一些 bind 族類 就會需要這些成員
bind 可以提供你像是 f(g(x), 2) or f(g(x), x) 這樣的函示組合
更進一步的話 可以參考 Loki or Boost
: 那些const有的沒的 也有點不求甚解…
const 就是明確指出不能修改該變數(參數)
像是 less, greater 這些 functor
一般狀況下不需要也不應該去修改傳給他們的參數
所以定義上會加 const 修飾
如果你加了const又修改 compiler 就會產生錯誤訊息
: 也不是很懂為何operator()要包在struct裡,
這是 functor 中文是仿函式(吧?) 的 pattern 可以去查查相關資訊
: 估計應該是要傳typename _Py給priority_queue…
像 priority_queue 是 sorted container 所以在宣告的時候就要給 comparator "type"
如同你現在的寫法:
priority_queue<MyClass*, vector<MyClass*>, TestArg3 > test;
而priority_queue的實體中(test)會建構一個TestArg3物件在compare的時候呼叫
但如果是要 sort vector container 時
e.g.
struct intPtrCmpLess
{
bool operator()(const int* lhs, const int* rhs){
return *lhs < *rhs;
}
};
vector<int*> IPVec;
std::sort(IPVec.begin(), IPVec.end(), intPtrCmpLess() );
^^^
這個時候是傳實體
或者你可以這樣寫
intPtrCmpLess ipcmp;
std::sort(IPVec.begin(), IPVec.end(), ipcmp);
: 就估且當做固定寫法吧>"<
: 不管怎樣,至少解決我的問題了:p
: 感謝大家的回答!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.47.68.32
※ 編輯: adxis 來自: 114.47.68.32 (11/26 17:34)
※ 編輯: adxis 來自: 114.47.68.32 (11/26 17:36)
※ 編輯: adxis 來自: 114.47.68.32 (11/26 17:39)