SORT LIST OF OBJECTS

How can I sort a list of objects by using a variable inside the class?

#include<iostream>

class DateTime {
private:
int year;
int month;
int day;
int hour;
int minute;
public:
(a lot of methods)
};


class Event {
public:
DateTime startTime;
DateTime endTime;
Event *next;
public:
Event(){};
(and other methods)
};

list<Event> list_of_events;
list<Event>::iterator it;

I WANT TO DO STH LIKE: list_of_events.sort();

But they ought to be sorted by using their StartTime (DateTime type)
The "smaller" their StartTime,the "sooner" they should begin,so the one with the "smallest" StartTime should be in the "top" of the list.

How can I achieve this?

Thank you.
Last edited on
So,can I overload > operator for DateTime and build a method to compare two DateTime objects (for example: bool DateTime::the_smaller_date()) and then use
list.sort(the_smaller_date()); ?
You wouldn't need to overload that.
you could have a "ConvertToSeconds()" method inside your DateTime class then your equivalent of this line in the example:
return ( first.length() < second.length() );

might look like this for you:
return ( first.ConvertToSeconds() < second.ConvertToSeconds() );

Something like that maybe?
Last edited on
I got it!

However,do I have to create the ConvertToSeconds() function?
calculate it using your other variables.

Edit: oops sorry i re-read what you typed. You don't have to create it, but you would have to come up with some other way of comparing two of your DateTime objects.
Last edited on
Topic archived. No new replies allowed.