C++在列表中对自定义对象进行排序

use*_*868 5 c++ sorting events list object

我在排序自定义类指针列表时遇到问题.我需要排序的类是事件.这些被分配一个随机时间,我需要按正确的顺序进行.

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

.........
Run Code Online (Sandbox Code Playgroud)

如果你能帮我解决这个问题,我将不胜感激!我已经被困在这几个小时了.

谢谢!

Mik*_*our 13

由于列表包含指针而不是对象,因此您必须提供自定义比较器来比较它们指向的对象.由于您使用的是a list,因此必须使用自己的sort方法:通用std::sort算法仅适用于随机访问序列.

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

或者,如果你被困在过去并且不能使用lambdas:

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

EventList.sort(CompareEventTime());
Run Code Online (Sandbox Code Playgroud)

如果列表包含对象(可能应该这样),那么提供比较运算符可能是有意义的:

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

std::list<Event> EventList;
//...
EventList.sort();
Run Code Online (Sandbox Code Playgroud)


Som*_*ude 0

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

  • 你的意思是“std::list&lt;&gt;::sort”。您不能在 `std::list` 上使用 `std::sort`,因为它没有随机访问迭代器。 (7认同)