当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《C++在列表中对自定义对象进行排序》经验,为你挑选了1个好方法。

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

#include 

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 EventList;
list::iterator it;

.........

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

谢谢!



1> Mike Seymour..:

由于列表包含指针而不是对象,因此您必须提供自定义比较器来比较它们指向的对象.由于您使用的是a 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 EventList;
//...
EventList.sort();

推荐阅读
手机用户2402852307
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有