1

For I project I'm working on I have a struct for a timestamp that contains multiple time values like seconds, minutes, hours etc.
I wanted to make a < operator and came up with the following monstrosity:

bool operator< (const RTCTime& lhs, const RTCTime& rhs) {
    if (lhs.getYear() > rhs.getYear()) return false;
    else if (lhs.getYear() == rhs.getYear()) {
        if (lhs.getMonth() > rhs.getMonth()) return false;
        else if (lhs.getMonth() == rhs.getMonth()) {
            if (lhs.getDayOfTheMonth() > rhs.getDayOfTheMonth()) return false;
            else if (lhs.getDayOfTheMonth() == rhs.getDayOfTheMonth()) {
                if (lhs.getHours() > rhs.getHours()) return false;
                else if (lhs.getHours() == rhs.getHours()) {
                    if (lhs.getMinutes() > rhs.getMinutes()) return fals;
                    else if (lhs.getMinutes() > rhs.getMinutes()) {
                        if (lhs.getSeconds() > rhs.getSeconds()) return false;
                    }
                }
            }
        }
    }
    return true;
}

I feel like it could be much simpler, but I have not idea how.

Naomi
  • 65
  • 6
  • Just use `std::tie`. Note when you have `return` inside `if` you do not have to write else statement, that will make your code much simpler – Slava May 17 '18 at 14:15
  • You may want to change the algorithm so that if all conditions are satisfied, the value `true` is returned and that `return false` is the last statement in your function. – Thomas Matthews May 17 '18 at 17:21

0 Answers0