5

我无法对自定义类指针列表进行排序。我需要排序的类是事件。这些被分配一个随机时间,我需要以正确的顺序执行它们。

#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;

.........

如果您能帮我解决这个问题,将不胜感激!我已经坚持了几个小时了。

谢谢!

4

2 回答 2

13

由于列表包含指针而不是对象,因此您必须提供自定义比较器来比较它们指向的对象。而且由于您使用的是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();
于 2013-05-12T13:04:24.640 回答
0

你应该用std::sort. 您可以创建一个自定义比较器函数,将其作为第三个参数传递给该std::sort函数,或者您可以<为您的类创建一个运算符重载并且std::sort自然而然地工作。

于 2013-05-12T12:49:39.710 回答