Difference between these two functions that find Palindromes....
Posted
by
Moin
on Stack Overflow
See other posts from Stack Overflow
or by Moin
Published on 2011-01-10T16:43:07Z
Indexed on
2011/01/10
16:53 UTC
Read the original article
Hit count: 150
c++
I wrote a function to check whether a word is palindrome or not but "unexpectedly", that function failed quite badly, here it is:
bool isPalindrome (const string& s){
string reverse = "";
string original = s;
for (string_sz i = 0; i != original.size(); ++i){
reverse += original.back();
original.pop_back();
}
if (reverse == original)
return true;
else
return false;
}
It gives me "string iterator offset out of range error" when you pass in a string with only one character and returns true even if we pass in an empty string (although I know its because of the intialisation of the reverse variable) and also when you pass in an unassigned string for example:
string input;
isPalindrome(input);
Later, I found a better function which works as you would expect:
bool found(const string& s)
{
bool found = true;
for (string::const_iterator i = s.begin(), j = s.end() - 1; i < j; ++i, --j) {
if (*i != *j)
found = false;
}
return found;
}
Unlike the first function, this function correctly fails when you give it an unassigned string variable or an empty string and works for single characters and such...
So, good people of stackoverflow please point out to me why the first function is so bad...
Thank You.
© Stack Overflow or respective owner