I'm learning C++, and one of the exercices (Accelerated c++) is to code a small program which finds palindromes.
To do this, I've created a vector holding a few words, and I'm then iterating over this vector to find palindromes. While iterating, I'm creating a copy of each word, reversing it, and then comparing if the reversed copy matches the origin word.
using namespace std;
vector<string> palindrome(vector<string> v){
for(std::vector<string>::iterator iter = v.begin(); iter != v.end(); ++iter){
string reversed_word;
for(int i = iter->size(); i >= 0; i--){
reversed_word += (*iter)[i];
}
if (!(*iter).compare(reversed_word)){
cout << reversed_word << endl;
}
cout << reversed_word << endl;
cout << *iter << endl;
}
return v
}
int main(){
vector<string> dictionnary;
dictionnary.push_back("coloc");
dictionnary.push_back("elle");
dictionnary.push_back("php");
dictionnary.push_back("shahs");
dictionnary.push_back("bonjour");
dictionnary.push_back("random");
palindrome(dictionnary);
return 0;
}
However, the condition !(*iter).compare(reversed_word)
doens't return what's expected for words that are palindromes. To check, I've displayed the words and the reverse words, and they do match.
What am I missing here ?