C++ : Suppose I have a user-defined type Date, which has member variables int y, int m, and int d. I also have a vector dates of type Date. I want to use sort(dates.begin(), dates.end)) to sort the vector from the earliest date to the latest date, but I need to define first how sort() will do its job in this case. How do I write the overloading function inside the Date class (i.e. how do I write Date's member function bool operator < ... etc.)?
if you're using a structure struct Date { int y; int m; int d; }; then you can define a function to compare the Dates bool DateComparer (const Date& date1, const Date& date2) { if(date1.y < date2.y) { return true; } else if(date1.y == date2.y && date1.m < date2.m) { return true; } else if(date1.y == date2.y && date1.m == date2.m && date1.d < date2.d) { return true; } return false; } #include <algorithm> ... namespace std ... etc vector<Date> dates; ... insert your dates sort(dates.begin(), dates.end(), DateComparer); but if you want to overload the < operator in a class... class Date { // data members ... public: bool operator < (const Date& date) const { if(this->y < date.y) { return true; } else if(this->y == date.y && this->m < date.m) { return true; } else if(this->y == date.y && this->m == date.m && this->d < date.d) { return true; } } }; then sort(dates.begin(), dates.end()); should do the trick, hope this helps =)
Join our real-time social learning platform and learn together with your friends!