简体   繁体   English

C ++-为学校建立我自己的String类,无法正确重载<运算符

[英]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): 这就是我现在所拥有的(str是一个动态的,以null结尾的char数组):

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). 基本上,我只需要比较两个以null结尾的char数组,看看哪一个较小(没有任何库)。

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): 虽然两个字符串的第n个字符相同(以0开头的n递增):
  2. If the n th character of both strings is '\\0' the strings are obviously the same, otherwise: 如果两个字符串的第n个字符均为'\\0'则字符串显然相同,否则:
  3. Otherwise, compare the n th characters as unsigned values, to determine the result of the comparison. 否则,将第n个字符作为无符号值进行比较,以确定比较结果。

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 请注意,如果您需要正确处理国家字母(通常值> 127),则需要将lr类型更改为unsigned char

But easier solution would be: 但是更简单的解决方案是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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