看板 C_and_CPP 關於我們 聯絡資訊
※ 引述《chun0826 (蛋頭￾ ︩》之銘言: : ※ 引述《khoguan (Khoguan Phuann)》之銘言: : : 是的。list 中的 sort() 有兩個,一個不需參數的就是 : : aecho哥講的那樣使用就對了,很簡單。另一個要參數的, : : 就比較複雜,我寫了一個完整的程式供參考: 我真是小題大作,弄了複雜難懂的寫法造成原po的困擾。 真是不好意思。以下是簡單易懂版。技巧就是透過 global function 來包裹 member function。但願能解決他的問題。 理論上,這樣寫執行效率會比較差一點。但若資料不是極多, 應該感覺不出來。畢竟易理解較重要。 // using function pointer for list.sort() #include <iostream> #include <list> #include <iterator> using namespace std; class MyObj { public: MyObj(int i=0) : data(i) {} bool comp(const MyObj& other) const { // 假設所用的比較函式名為 comp if (this->data < other.data) return true; else return false; } friend ostream& operator<< (ostream& os, const MyObj& my); private: int data; }; ostream& operator<< (ostream& os, const MyObj& my) { return os << my.data; } // 原先的複雜寫法,簡單改用 global function 來做 bool mem_comp(const MyObj& a, const MyObj& b) { return a.comp(b); } int main() { list<MyObj> mylist; for (int i = 9; i >= 1; --i) mylist.push_back(MyObj(i)); // 放進 9 個元素做測試用 mylist.sort(&mem_comp); // 注意用法,不寫 & 也行 } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.130.208.166 ※ 編輯: khoguan 來自: 218.163.154.74 (01/23 20:31)