In the first one you're mixing signed and unsigned datatypes. Here's a way to do it manually:
#include <iostream>
#include <string>
using namespace std;
template <class Iter>
bool is_palindrome( Iter first, Iter last )
{
while ( ( first != last ) && ( first != --last ) )
{
if ( *first != *last ) return false;
++first;
}
return true;
}
int main()
{
string s( "123210" );
bool palindrome = is_palindrome( s.begin(), s.end() );
cout << ( palindrome ? "Palindrome!" : "Not a palindrome..." ) << endl;
}
The beauty of this over yours is that I'm not limiting this to strings, and I can choose sections of the string based on the iterator positions.
I don't need the explanation, but perhaps more explanation would help others understand the code you're posting, otherwise what's the purpose of this thread? You didn't explain that the stream you're using for the string by default delimits by spaces, so nobody is going to understand how any of that works unless they already know how it works, in which case this thread would be of no benefit to the more experienced programmers either. I'm just saying.