Graham Slick Graham Slick - 1 year ago 61
C++ Question

Comparison of strings shows not equal

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;

return 0;

However, the condition
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 ?

Answer Source

How many times does this loop iterate?

for(int i = (*iter).size(); i >= 0; i--)

You probably want size()-1 so it won't look past the end of the word.

Likewise, iter <= v.end() is seldom right. end never points to anything; it is always invalid. The idiom is != v.end().

Also, if the function does not return a value, its return type should be void.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download