简体   繁体   中英

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

You can take advantage of null-terminated strings to simplify the basic algorithm to:

  1. While the n th character of both strings are the same (incrementing n starting with 0):
  2. If the n th character of both strings is '\\0' the strings are obviously the same, otherwise:
  3. Otherwise, compare the n th characters as unsigned values, to determine the result of the comparison.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM