reverse_iterator problems

Hi

I am having some trouble with a string::reverse_iterator, my objective is to reverse a string using the iterator instead of reverse(). I know the problem lies in the loop on line 36, really appreciate some help.

Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <string>

using std::string;
using std::cout;
using std::cin;
using std::endl;

bool palindrome(const string & str);

int main()
{
	string input;

	cout << "Please enter a word to check if its a palindrome: (\"quit\" to quit)";

	while(cin >> input && input != "quit")
	{
		if(palindrome(input))
			cout << input << " \bis\b a palindrome.\n";
		else
			cout << input << " is \bnot\b a palindrome.\n";

		cout << "Please enter a word to check if its a palindrome: (\"quit\" to quit)";
	}

	return 0;
}


bool palindrome(const string & str)
{
	string temp;
	string::reverse_iterator revit;

	for(revit = str.rbegin(); revit < str.rend(); revit++)
	{
		temp += *revit;
	}

	if(str == temp)
		return true;
	else
		return false;
}
Last edited on
Use the following loop

for( revit = str.rbegin(); revit != str.rend(); revit++ )
instead of

for(revit = str.rbegin(); revit < str.rend(); revit++)
Also it is much simpler to write

1
2
3
4
inline bool palindrome( const string &str )
{
	return ( str == string( str.rbegin(), str.rend() ) );
}
Last edited on
Thanks vlad, I was using the != before I changed over to < to see if that was the problem.

The problem is actually in this:
 
bool palindrome(const string & str)


iterator can't assign const to non-const, needs to be changed to:
 
bool palindrome(string & str)


and you're right about the inline function, much better and I hadn't thought of that, but purpose of the exercise was to play with iterators and get familiar with them.


Thanks!
Topic archived. No new replies allowed.