F.J.K. schrieb:
IIRC, for an int a[10] there are following equivalences
a.begin() == &a[0];
a.end() == &a[10];
a.rbegin() == &a[9];
a.rend() ==&a[-1]
pls correct me if I'm wrong (other than iterators not really being
pointers).
Ok, I am wrong and I correct myself ;-)
A reverse iterator contains a normal iterator current, so that
a.begin() == a.rend().current
a.end() == a.rbegin().current
As I already wrote, this would segfault all over the place (as indeed
the OP experiences). As a "clever solution" the STL implements the
*reverse_iterator operator to return *(current-1). The
reverse_operator.base() function however returns current directly,
which is the reason why above code (which doesn't compile btw.)
segfaults. The solution is obvious, only use reverse_iterator.base()-1.
The above example in its corrected form:
#include <iostream>
#include <string>
using namespace std;
string TrimRight(const string& strin)
{
string str = strin;
string::reverse_iterator it = str.rbegin();
while(it!=str.rend() && *it==' '){
str.erase(it.base()-1);
it = str.rbegin();
}
return str;
}
int main()
{
string str = "hello ";
cout << str << "|"<< endl;
str = TrimRight(str);
cout << str << "|"<< endl;
return 0;
}