Reputation: 409
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).
Upvotes: 0
Views: 87
Reputation: 44238
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;
Upvotes: 1
Reputation: 118292
You can take advantage of null-terminated strings to simplify the basic algorithm to:
n
th character of both strings are the same (incrementing n
starting with 0):n
th character of both strings is '\0'
the strings are obviously the same, otherwise:n
th characters as unsigned values, to determine the result of the comparison.Upvotes: 2