I am using C++ erase remove idiom and facing a weird problem.
If I access element using string index result is not as expected.
string str = "A man, a plan, a canal: Panama";
str.erase(remove(str.begin(), str.end(), str[1]), str.end());
Result : Aman, a plan, a canal: Panaa
and if I use as below, result is as expected.
string str = "A man, a plan, a canal: Panama";
str.erase(remove(str.begin(), str.end(), ' '), str.end());
Result : Aman,aplan,acanal:Panama
>Solution :
Look at the signature of std::remove:
template< class ForwardIt, class T >
ForwardIt remove( ForwardIt first, ForwardIt last, const T& value );
The value is passed by const reference, therefore after removing first space your str[1] points to a wrong memory. It’s unsafe to access container elements while modifying the container.