Hello programmers!
After covering the basics of STL, I decided to complete the following assignment: Write a function template palindrome that takes a vector parameter and returns true or false according to whether the vector does or does not read the same forward a backward.
So, for example, a vector with "1,2,3,2,1" would be a palindrome, but a vector containing "1,2,3,4" is not.
I accidentially found out that you could do this [on StackOverFlow],
template <typename T> bool isPalindrome(const T& theRef)
{
//solution found on the internet
//check to see if theRef's contents is a palindrome
return equal(theRef.cbegin(),theRef.cend(),theRef.crbegin());
}
but I did not want to "cheat" and create my own, so this is what I did:
template <typename T> bool isPalindrome(const T& theRef)
{ /* ..solution found on StackOverflow
//check to see if theRef's contents is a palindrome
return equal(theRef.cbegin(),theRef.cend(),theRef.crbegin());
*/
typename T::const_iterator forwardTIterator;
typename T::const_reverse_iterator backwardTIterator;
/*
Iterate over list with both iterators being set to
respective positions: forwardTIterator to beginning, and
backwardTIterator to the last item (one in front of the
last (empty) slot.
*/
for (forwardTIterator=theRef.cbegin(), backwardTIterator=(theRef.crbegin()+1);
forwardTIterator!=theRef.cend();
forwardTIterator++,backwardTIterator++) //move iterators in their respective directions- forwardTIterator forward, and backwardTIterator backwards
{
if (*forwardTIterator != *backwardTIterator)//check to see if they are equal to each other
//the defreferenced items are NOT equal to each other, therefore not palindromes
return false;
}
return true;
}
The logic is that each iterator would iterate over the vector in opposite directions, and that after each step, each iterator would compare the item being read to the other's. If they are not equal, then there is no chance that there is a palindrom stored in the vector.
I understand that there are better ways to do it, and I am actually considering creating a function with recursion- just for fun, but could any help me understand why when I implement the following with the function shown above, I get a wrong result?
Here's what I have in addition to the function shown above:
// Program that takes the vector parameter of a number and
// tests it to see if its a palindrome
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
template <typename T> bool isPalindrome(const T&);
template <typename T> void print(const T&);
int main()
{
vector<int> num={1,2,2,1}; //create vector num with digits
cout << "Number stored in vector 'num' is: ";
print(num);
cout << "\n\nChecking to see if it's a palindrome..." << endl;
cout << (isPalindrome(num) ? "It is a palindrome!":"It is not a palindrome.") << endl;
return 0;
}
template <typename T> void print(const T& tRef)
{
//output tRef's contents
for (const auto& item:tRef)
cout << item;
cout << endl;
}
Many thanks!