'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?
Solution 1:[1]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | paolo |
