简体   繁体   中英

C++ Char Class Operator< function compare

bool String::operator < (const String &s) const 
{
int len1 = s.getLength();
int len2 = this->getLength();
int cap;
if(len1>len2) cap = len2;
else cap = len1;
int index=0;
for (int i =0; i < cap;i++)
    if (this->buffer[i] != s[i])
        index =i;
for (int i= index; i < cap; i++)
    if (this->buffer[i] < s[i])
        return true;
for (int i= index; i < cap; i++)
    if (this->buffer[i] > s[i])
        return false;
if (*this == s)
    return false;
if (len2>len1)
    return false;
if (len2<len1)
    return true;
}

I have been working with this overloading operator< that compares two strings.

It's working successfully. I test every case that possible.

But when I F7 the program, it still shows up 'String::operator<': not all control paths return a value.

Please tell me what am I missing in this function?

If your loops don't return , and if *this == s is false (you shouldn't be doing that comparison in this function), and if len2>len1 and len2<len1 are both false (meaning len2==len1 is true), then you are indeed missing a final return , which is what the compiler is warning you about.

bool String::operator < (const String &s) const 
{
    ...

    if (len2>len1)
        return false;
    if (len2<len1)
        return true;

    // IF YOU REACH HERE, THERE IS NO RETURN!
}

That being said, your code can be simplified a bit:

bool String::operator < (const String &s) const 
{
    int len1 = this->getLength();
    int len2 = s.getLength();
    int cap = (len1 < len2) ? len1 : len2;
    for (int i = 0; i < cap; ++i) {
        if (this->buffer[i] != s[i]) {
            return (this->buffer[i] < s[i]);
        }
    }
    return (len1 < len2);
}

Alternatively, you can use std::mismatch() :

#include <algorithm>

bool String::operator < (const String &s) const 
{
    int len1 = this->getLength();
    int len2 = s.getLength();
    int cap = std::min(len1, len2);
    const char* buffer_end = this->buffer + cap;
    std::pair<const char*, const char*> ret = std::mismatch(this->buffer, buffer_end, s.buffer);
    return (ret.first != buffer_end)
        ? (*ret.first < *ret.second)
        : (len1 < len2);
}

Or, in C++14 and later:

#include <algorithm>

bool String::operator < (const String &s) const 
{
    int len1 = this->getLength();
    int len2 = s.getLength();
    const char* buffer_end = this->buffer + len1;
    const char* s_end = s.buffer + len2;
    auto ret = std::mismatch(this->buffer, buffer_end, s.buffer, e_end);
    return ((ret.first != buffer_end) && (ret.second != s_end))
        ? (*ret.first < *ret.second)
        : (len1 < len2);
}

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