C++ Sorting Custom Objects in a list

后端 未结 2 1973
迷失自我
迷失自我 2020-12-07 03:19

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.

相关标签:
2条回答
  • 2020-12-07 03:50

    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;});
    

    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();
    
    0 讨论(0)
  • 2020-12-07 03:53

    You should to that with std::sort. You can either make a custom comparator function that you pass as third argument to the std::sort function, or you can make a < operator overload for your class and std::sort will work naturally.

    0 讨论(0)
提交回复
热议问题