Re: overload operator < 來排序

看板Programming作者 (陳揚和)時間15年前 (2009/04/04 13:17), 編輯推噓0(001)
留言1則, 1人參與, 最新討論串9/9 (看更多)
再次感謝前輩們的指導 果然又是我c++沒學好 不應該用function pointer來做 而是寫個functor..很容易就可以使用在functor中有pointer利用外部資料排序 順便分享一下..除了sort, 原本覺得不太可能的 lower_bound這種std function也可以 靠寫特殊的functor 比較不同類型的data type 達到 附上我簡單的test example // Test for using functor of sorting and binary search #include "stdafx.h" #include <algorithm> #include <iostream> using namespace std; class CcompareFunctor4Sort { public: double* grade; CcompareFunctor4Sort(double* grade) { this->grade = grade; } bool operator () (int a, int b) { return(grade[a] < grade[b]); } }; class CcompareFunctor4BinarySearch { public: double* grade; CcompareFunctor4BinarySearch(double* grade) { this->grade = grade; } bool operator () (unsigned int a, unsigned int b) { return(grade[a] < grade[b]); } }; class CcompareFunctor4BinarySearch2 { public: double* grade; CcompareFunctor4BinarySearch2(double* grade) { this->grade = grade; } bool operator () (unsigned int a, double b) { return(grade[a] < b); } }; int _tmain(int argc, _TCHAR* argv[]) { int student[] = {0, 1, 2, 3, 4, 5, 6, 7, 8}; double grade[] = {5.1, 3.1, 1.1, 2.1, 4.1, 2.1, 2.1, 2.5, 2.1}; sort(&student[0], &student[0] + 8, CcompareFunctor4Sort(grade)); // The correct sort is 2, 3, 5, 1, 4, 0 for(int i = 0; i < 8; i++ ) { cout << student[i] << ',' << grade[student[i]] << endl; } int* l = lower_bound(&student[0], &student[0] + 8, 5.2, CcompareFunctor4BinarySearch2(grade)); cout << *l << endl; return 0; } ※ 引述《LPH66 ((short)(-15074))》之銘言: : ※ 引述《adrianshum (Alien)》之銘言: : : 我沒記錯的話, 現有 Std lib 裡有不少都已 : : 經有提供你所說的 'comparison function', : : 用來讓沒有提供 < operator 的東西能依一個 : : 外來傳入的 less function 來作比較 (及 sort) : : 可以去看看 map 怎樣做法. 通常很多情況下都 : : 不是真的餵 function pointer, 而是餵 functor : struct object //其實用 class 也不會怎樣 自己控管好 accessibility 就好 : { : int x,y,z; : }; : bool compare1(const object &a, const object &b) : { : return a.x>b.x; : } : bool compare2(const object &a, const object &b) : { : return a.y<b.y; : } : class compare3 //這是一個functor! : { : public: : bool operator () (const object &a, const object &b) : { : i -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 128.125.87.33 ※ 編輯: sorryChen 來自: 128.125.87.33 (04/04 13:18) ※ 編輯: sorryChen 來自: 128.125.87.33 (04/04 13:58)

04/04 14:59, , 1F
話說取upper_bound時functor要改反過來
04/04 14:59, 1F
文章代碼(AID): #19rkreQW (Programming)
討論串 (同標題文章)
文章代碼(AID): #19rkreQW (Programming)