Ask your own question, for FREE!
Computer Science 16 Online
OpenStudy (anonymous):

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.)?

OpenStudy (anonymous):

First compare years, then months, then days. If at any stage they are not equal, return a value to say which one is larger. If you get past the days comparison and they're still equal, return 0. (Unless you're really just interested in strictly less than, in which case say it's not less than.)

OpenStudy (anonymous):

I wish I could do that, in fact I've tried that, but when I run the program it gives me a runtime error, "invalid operator < " here's my bool operator function: bool operator < (const Date& a) const { if (y < a.y) if (m < a.m) return d < a.d; }

OpenStudy (anonymous):

Does it need to be scoped to the class (Date::operator <(const Date& a) const)? It's been a while since I've done C++. Also that function isn't correct. It doesn't always return a value. Write the nested "if"s on different lines, with correct indentation, and it should become apparent. And that should have caused a compile-time error, not a runtime error (I would think).

OpenStudy (anonymous):

that's already inside my Date class. I'm really not sure how you meant the "always return a value." let me give scenarios of what I've tried already: bool operator < (const Date& a) const { return d < a.d; //no errors, but sorts only the days } bool operator < (const Date& a) const { if (y < a.y) return m < a.m; //run-time error, using while () produces same error } bool operator < (const Date& a) const { return y < a.d; //no errors, but doesn't sort the dates correctly return m < a.m; return d < a.d; } bool operator < (const Date& a) const { return y < a.d && m < a.m && d< a.d; //no errors, doesn't sort the dates correctly }

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!