Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Comparing characters at the same index of two strings

I am trying to compare the characters of two strings at a given index. However, I am getting the following error:

Line 9: Char 26: error: invalid operands to binary expression ('const __gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type' (aka 'const char') and 'const std::__cxx11::basic_string<char>')
                if (s[i] != letter) { return s.substr(0, i); }
                    ~~~~ ^  ~~~~~~

Here is my code:

string longestCommonPrefix(vector<string>& strs) {
    auto comp = [](const string& a, const string& b) { return a.size() < b.size(); };
    const auto smallest = min_element(strs.begin(), strs.end(), comp);
    for (int i = 0; i < smallest->size(); ++i) {
        const auto letter = smallest[i];
        for (const auto& s : strs) {
            if (s[i] != letter) { return s.substr(0, i); }  // <- error occurs here
        }
    }
    return smallest;
}

Could someone please explain why this does not work?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In your code, smallest is a

std::vector<std::string>::iterator const

which is a random access iterator, hence provides operator[].

However,

smallest[i]

is equivalent to

*(smallest + i)

so it will return a reference to the i-th string after the one pointed to by
smallest instead of the i-th character of the string pointed to by
smallest (which is what you want).

To get the i-th character of the string pointed to by smallest, you should
first deference it:

(*smallest)[i]

And you should deference it as well in the return statement.


Also, I recommend you pass strs as a reference to const and check that smallest is not the end iterator (which may occurr if the input vector is empty):

string longestCommonPrefix(vector<string> const& strs) {
    auto comp = [](const string& a, const string& b) {
        return a.size() < b.size();
    };

    const auto smallest = std::min_element(strs.begin(), strs.end(), comp);
    if (smallest == strs.end()) return "";

    for (int i = 0; i < smallest->size(); ++i) {
        const auto letter = (*smallest)[i];
        for (const auto& s : strs) {
            if (s[i] != letter) return s.substr(0, i);
        }
    }

    return *smallest;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading