C ++在列表中排序自定义对象 [英] C++ Sorting Custom Objects in a list

查看:118
本文介绍了C ++在列表中排序自定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在排序自订类别指针清单时遇到问题。我需要排序的类是事件。这些被分配一个随机时间,我需要按正确的顺序。

I am having trouble sorting a list of custom class pointers. The class I need to sort are events. These get assigned a random time and I need to do them in the right order.

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

.........

我排序这将是非常感谢!我已经坚持这个几个小时了。

If you could help me sort this out it would be much appreciated! I've been stuck on this for hours now.

谢谢!

推荐答案

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

Since the list contains pointers, rather than objects, you'll have to provide a custom comparator to compare the objects they point to. And since you're using a list, you have to use its own sort method: the generic std::sort algorithm only works on random-access sequences.

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

或者,如果你在过去无法使用lambdas:

or, if you're stuck in the past and can't use lambdas:

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

EventList.sort(CompareEventTime());

如果列表包含对象(可能应该),那么提供比较

If the list contained objects (as it probably should), then it might make sense to provide a comparison operator instead:

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

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

这篇关于C ++在列表中排序自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆