[語法] STL sort 在一個 Class 裡面含很多priv …

看板C_and_CPP (C/C++)作者 (BlackMatrix)時間16年前 (2009/10/04 02:14), 編輯推噓3(309)
留言12則, 4人參與, 最新討論串1/6 (看更多)
有一個問題困擾我很久, 1. 要怎麼Sort一個Class裡面包含多很多int, double之類的 假如我用sort (GNF_vector.begin(),GNF_vector.end()) 它就不高興, 說就會說cannot convert parameter 1 from GNF to const int& 假如說我想要單單獨依照某個數字,Lat,排列我整個vector: Vector裡面包含了7種double跟int, 那我想用其中一種數字排列大家 GNF_vector[i].dms_lat....GNF_vector[i].lat之類的 可是Sort裡面不吃我整個Vector, 我也不知道該怎麼叫他只用其中一種數字排列我整個 Vector 另外教授也只說, 只能用Stl::sort, 而且不能在class裡面加operator < 2. Template用再一個vector 裡面包含Class我也不會 我有兩個Template, 教授說一定要用Template做 template <class C> class LessThanByLat { public: bool operator() (C b) { return (b[1].dms_lat<b[2].dms_lat); } //c=GNF_vector, WRONG!!! }; 和 template <class C, class If, class Sorting> void Modify_If (C a, If c, Sorting d) { if (a(c)) { cout << "Yes" << endl; //Modify_If(LessThanByLat<bool>(), GNF_vector, 3); //a=LessThanByLat //c=GNF_vector } } 意思就是說, 如果我裡面的dms_lat第一個小於第二個, 那就是意思要我Sort整個Vector 我如果在我的int main寫進去 { Modify_If(LessThanByLat<bool>(),GNF_vector,NULL); } 重點是我想傳我的Vector進去我的LessThanByLat裡面 我發現說Vector<typename> b 那個b不可以等於又是那個Vector, 可是如果我寫 Modify_If(LessThanByLat<bool>(),GNF,NULL) GNF是我的Class Name 那就等於 GNF b 可是我想要我的B等於我的Vector, 我怎麼讓B等於我的Vector, 還是只能寫在heap裡面? 謝謝, 如果各位看得懂得請麻煩提示我一下, 我做了三個小時在這個上面了 看了C++ Primer Plus跟Data Structures and Problem solving using C++都沒用 救命阿 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 71.183.68.195

10/04 02:31, , 1F
不能動operator < 就自己寫個compare function/functor
10/04 02:31, 1F

10/04 02:31, , 2F
吧...
10/04 02:31, 2F

10/04 02:37, , 3F
std::less ...
10/04 02:37, 3F

10/04 02:45, , 4F
L大, 那個LessThanByLat等於Compare Functor, 可是
10/04 02:45, 4F

10/04 02:45, , 5F
我好像寫錯了...
10/04 02:45, 5F

10/04 02:45, , 6F
Compare Functor是教授規定要做的 = =
10/04 02:45, 6F

10/04 02:46, , 7F
謝謝~~
10/04 02:46, 7F

10/04 03:00, , 8F
其實重點是 private member ...
10/04 03:00, 8F

10/04 03:55, , 9F
那該怎麼辦, 寫在Heap裡面會有用嗎?
10/04 03:55, 9F

10/04 03:57, , 10F
還是說繼續寫在Static可是用getLat之類的?
10/04 03:57, 10F

10/04 03:59, , 11F
int getLat {return lat};之類的
10/04 03:59, 11F

10/05 00:17, , 12F
getLat() + compare function 正解.. ^^
10/05 00:17, 12F
現在我完全改進我的Functor, 變成 template <class C> class LessThanByLat { public: bool operator() (C lhs, C rhs) { return (lhs.getLat()<rhs.getLat()); } }; 跟 sort (GNF_vector.begin(), GNF_vector.end(), LessThanByLat<bool>()); 我想要我的vector裡面以LAT這個數字以大到小排列, 目前我這樣寫, 看看該怎麼辦 成功 如果有想法的拜託請給點提示~~~~ (雖然我知道我上面那串Code寫錯了) ※ 編輯: BlackMatrix 來自: 71.183.68.195 (10/05 04:55) 我解決這個問題了 class LessThanByLat { public: bool operator() (GNF& lhs,GNF& rhs) { return (lhs.getLat()<rhs.getLat()); } }; sort (GNF_vector.begin(), GNF_vector.end(), LessThanByLat()); 謝謝各位的幫助 ※ 編輯: BlackMatrix 來自: 71.183.68.195 (10/05 07:38)
文章代碼(AID): #1AnvINfJ (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1AnvINfJ (C_and_CPP)