#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
string s = "Haven't got an idea why.";
auto beg = s.begin();
auto end = s.end();
while (beg < end)
{
cout << *beg << '\n';
if (*beg == 'a')
{//whithout if construct it works perfectly
beg = s.erase(beg);
}
++beg;
}
return 0;
}
Why if I erase one or more chars from this string this code breaks? I suppose it has something to do with returned iterator after erase operation being created at higher address than end iterator but I’m not sure and it surely isn’t right behaviour. Or is it?
There are several problems with this code.
s.end(); it changes as you delete elements.beg < end. The idiomatic approach is to writebeg != end. If you try to iterate pastend, the result is undefined, and a debug version of the string library may deliberately crash your process, so it is meaningless to use<.s.erase(beg)might bes.end(), in which case++begtakes you past the end.Here’s a (I think) correct version:
EDIT: I suggest accepting FredOverflow’s answer. It is simpler and faster than the above.