#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
usingnamespace std;
vector<string> ret;
vector<string> find_palindrome ( const string& s)
{
// Iterator for the first and last character
string::const_iterator i = s.begin();
string::const_iterator j = s.end() - 1;
// Check if the first and last character is the same
if (*i == *j )
{
/* If the current pair of character is the same, check the next pair by incrementing i and decrementing j
Terminate the loop if the current pair is different or i becomes larger than j (meaning it's a palindrome) */
while (*i == *j && i <= j)
{
++i; --j;
// If i is larger than j, copy the word into ret
if (i > j)
{
ret.push_back(s);
}
}
// reset the iterator for the next word
i = s.begin();
j = s.end() - 1;
}
return ret;
}
int main()
{
vector<string> palindrome;
string str;
while (cin >> str)
{
find_palindrome(str);
}
palindrome = ret;
sort (palindrome.begin(), palindrome.end());
vector<string>::const_iterator iter = palindrome.begin();
cout << "The word that is a palindrome is: " << endl;
while (iter != palindrome.end())
{
cout << *iter << endl;
++iter;
}
if (palindrome.size() == 0)
{
cout << "No palindrome found" << endl;
}
}
It works just fine, but the problem is my teacher told me to revise the code by making it more efficient, and not to use the vector<string> ret
Please help me because i don't know how to revise it without using ret..
well thats easy. just add a vector parameter in the find_palindrome function, and pass palindrome as an argument with the string. Doesnt make sense to assign a global variable to a local one.
// Iterator for the first and last character
string::const_iterator i = s.begin();
string::const_iterator j = s.end() - 1;
// Check if the first and last character is the same
if (*i == *j )
{
/* If the current pair of character is the same, check the next pair by incrementing i and decrementing j
Terminate the loop if the current pair is different or i becomes larger than j (meaning it's a palindrome) */
while (*i == *j && i <= j)
{
++i; --j;
// If i is larger than j, copy the word into ret
if (i > j)
{
ret.push_back(s);
}
}
// reset the iterator for the next word
i = s.begin();
j = s.end() - 1;
}
Why not simply use reverse iterator and the string constructor?
apple is palindrome = false
racecar is palindrome = true
mom is palindrome = true
sauce is palindrome = false
redrum is palindrome = false
tattarrattat is palindrome = true