conjenks conjenks - 1 month ago 7
C++ Question

C++ - Building my own String class for school, can't overload < operator correctly

This is what I have right now (str is a dynamic, null-terminating char array):

bool String::operator<(const String& rhs) const {
if (str == rhs.str)
return false;
int i = 0;
while (str[i] != '\0' && rhs[i] != '\0') {
if (str[i] > rhs[i])
return false;
++i;
}
return true;
}


This passes most tests, but it fails on:

String s1("abc");
String s2("abcde");

assert(!(s2 < s1));


No matter how I alter the function it always seem to fail one test or another. How would YOU overload this operator? Basically I just need to compare two null-terminating char arrays and see which one is the lesser (without any libraries).

Answer

If you change your loop to:

int i = 0;
while (true) {
    char l = str[i];
    char r = rhs.str[i++];
    if( l < r ) return true;
    if( l == 0 || l > r ) return false;
}

it should work. Note if you need to handle national alphabets properly, that usually has values > 127, you need to change l and r type to unsigned char

But easier solution would be:

return strcmp( str, rhs.str ) < 0;