2013-05-12 77 views
5

我在排序自定義類指針列表時遇到問題。我需要排序的類是事件。這些被分配一個隨機時間,我需要按照正確的順序進行。C++在列表中排序自定義對象

#include <list> 

Class Event{ 
public: 
float time; // the value which I need to sort them by 
int type; // to indicate which event i'm dealing with 

Event(float tempTime, int tempType) 
{ 
    time = tempTime; 
    type = tempType; 
} 


int main(){ 

std::list<Event*> EventList; 
list<Event*>::iterator it; 

......... 

如果你能幫我解決這個問題,將不勝感激!我一直堅持這幾個小時。

謝謝!

回答

1

你應該與std::sort。您可以創建一個自定義的比較器函數,並將其作爲函數的第三個參數傳遞給函數,也可以爲您的類創建一個<運算符超載,並且std::sort將自然工作。

+6

你的意思是'std :: list <> :: sort'。你不能在'std :: list'上使用'std :: sort',因爲它沒有隨機訪問迭代器。 – 2013-05-12 12:58:18

+0

我曾嘗試使用自定義比較器功能,但它不適用於我。 (並使用list.sort)j – user2374868 2013-05-12 13:01:53

+2

另外,重載'operator <'將無助於排序指針。 – 2013-05-12 13:02:45

10

由於列表包含指針而不是對象,因此您必須提供自定義比較器來比較它們指向的對象。由於您使用的是list,因此您必須使用自己的sort方法:通用std::sort算法僅適用於隨機訪問序列。

EventList.sort([](Event * lhs, Event * rhs) {return lhs->time < rhs->time;}); 

,或者,如果你停留在過去,不能用lambda表達式:如果列表中包含的對象

struct CompareEventTime { 
    bool operator()(Event * lhs, Event * rhs) {return lhs->time < rhs->time;} 
}; 

EventList.sort(CompareEventTime()); 

(因爲它可能應該),那麼它可能是有意義的提供一個比較運算符代替:

bool operator<(Event const & lhs, Event const & rhs) {return lhs.time < rhs.time;} 

std::list<Event> EventList; 
//... 
EventList.sort(); 
+0

非常感謝!最後一條評論讓我意識到我沒有任何理由使用指針。因此,我改變了它並實施了您的最後一個解決方案,現在它正在完美運行(順便說一句,最後的解決方案給我一個錯誤,只需要在運算符函數中的單個元素,所以我刪除了lhs並使用this->而不是 – user2374868 2013-05-12 15:20:30

+0

@ user2374868:是的,您可以使運算符成爲一個成員函數而不是我的兩個參數的非成員的例子 – 2013-05-12 19:15:37

+0

對於列表,使用List.Sort()而不是std :: Sort()在一小時後才意識到這一點 – 2016-01-30 20:13:40