-
Home
-
Palindrome function assignment solution implemented in C++
Complete the provided C++ program by debugging the function isPalindrome.
The function should determine if a vector of ints is a palindrome. For example, {1, 2, 3, 2, 1} and { 1, 2, 3, 3, 2, 1 } are palindromes but { 1, 2, 3, 4, 1 } and { 1, 2, 3, 4, 2, 1 } are not palindromes.
This program uses iterators. The function works in all cases except when an even-length palindrome is passed in.
The output should be:
False
False
True
true
The given code doesn't work right for the last case and produces this output:
false
false
true
false
Your job is to figure how the function uses iterators and fix the bug.
#include
#include
#include
#include
using namespace std;
bool isPalindrome(const vector & v);
int main() {
vector v1False{ 1, 2, 3, 4, 1 };
cout << boolalpha << isPalindrome(v1False) << endl;
vector v2False{ 1, 2, 3, 4, 2, 1 };
cout << boolalpha << isPalindrome(v2False) << endl;
vector v1True{1, 2, 3, 2, 1};
cout << boolalpha << isPalindrome(v1True) << endl;
vector v2True{ 1, 2, 3, 3, 2, 1 };
cout << boolalpha << isPalindrome(v2True) << endl;
system("pause");
return 0;
}
bool isPalindrome(const vector & v) {
if ( v.size() == 0 ) {
return true;
}
auto front = v.begin(); // first element of v.
auto rear = --v.end(); // last element of v.
// algorithm:
// iterators front and rear move towards center.
// if there is a mismatch, the loop ends
// if palindrome, front and rear both get to middle.
// as long as front and rear elements have the same value
// and front hasn't gone past rear, increment both.
for (; *front == *rear && front < rear; ++front, --rear) {
// no op
}
// check positions of front and rear.
// if there is a mismatch, it will happen
// before front passes rear.
return front >= rear;
}