我在排序自定义类指针列表时遇到了问题。我需要排序的类是事件。这些被分配了一个随机的时间,我需要按照正确的顺序来做。
#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;
.........如果你能帮我解决这个问题,我将不胜感激!我已经被困在这里好几个小时了。
谢谢!
发布于 2013-05-12 21:04:25
由于该列表包含指针,而不是对象,因此您必须提供一个自定义比较器来比较它们所指向的对象。由于您使用的是list,因此必须使用它自己的sort方法:通用的std::sort算法只适用于随机访问序列。
EventList.sort([](Event * lhs, Event * rhs) {return lhs->time < rhs->time;});或者,如果你停留在过去,不能使用lambdas:
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-12 20:49:40
你应该用std::sort实现这一点。您可以创建一个自定义的比较器函数,并将其作为第三个参数传递给std::sort函数,也可以为您的类创建一个<运算符重载,这样std::sort就会正常工作。
https://stackoverflow.com/questions/16507519
复制相似问题