If you want Palindrome(const string&)
to manipulate string reverse
you should pass it by reference.
#include <string>
#include <iostream>
using namespace std;
bool palindrome_internal( const string& s, string& reverse, int i )
{
if(i < s.size()){
reverse[i] = s[s.size()-(i+1)]; // first character in reverse is the last character in s
palindrome_internal( s , reverse , i + 1);
}
return s == reverse;
}
bool Palindrome(const string& s ){
string reversed { s }; // initialized here
return palindrome_internal( s , reversed , 0 ); // And passed to recursive function
}
int main()
{
cout << Palindrome( "example" ) << endl; // Not palindrome
cout << Palindrome( "repaper" ) << endl; // Palindrome
cout << Palindrome( "rotator" ) << endl; // Palindrome
cout << Palindrome( "madam" ) << endl; // Palindrome
cout << Palindrome( "" ) << endl; // Palindrome
cout << Palindrome( "" ) << endl; // Palindrome
}
online code
Your code actually a bit weird, because you are not calculating palindrome recursively, actually you are filling string reverse
recursively.
Maybe this simpler version suits better.
#include <string>
#include <iostream>
bool palindrome( const std::string& s, int i = 0 )
{
if ( i == s.size() )
return true;
return s[ i ] == s[ s.size() - i - 1 ] && palindrome( s , i + 1 );
}
int main()
{
using namespace std;
cout << palindrome( "example" ) << endl; // Not palindrome
cout << palindrome( "repaper" ) << endl; // Palindrome
cout << palindrome( "rotator" ) << endl; // Palindrome
cout << palindrome( "madam" ) << endl; // Palindrome
cout << palindrome( "" ) << endl; // Palindrome
cout << palindrome( "a" ) << endl; // Palindrome
}
online code