The following
#include <iostream>
#include <string>
void remove_duplicates ( std::string & s )
{
for (std::string::iterator it(s.begin()), offend(s.end()); it != offend; ++it)
{
std::string::iterator temp = it;
while (++it != offend && *it == *temp);
if ((it-temp)>1) s.erase(temp, it);
}
}
int main()
{
std::string str = "aaabbcaaaaa";
remove_duplicates(str);
std::cout << str; /* Expected output: "abca" */
return 0;
}
is producing the error
/usr/local/lib/gcc/i686-pc-linux-gnu/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h:1154: __gnu_cxx::__normal_iterator::other::pointer, std::basic_string<_CharT, _Traits, _Alloc> > std::basic_string<_CharT, _Traits, _Alloc>::erase(__gnu_cxx::__normal_iterator::other::pointer, std::basic_string<_CharT, _Traits, _Alloc> >, __gnu_cxx::__normal_iterator::other::pointer, std::basic_string<_CharT, _Traits, _Alloc> >) [with _CharT = char, _Traits = std::char_traits, _Alloc = std::allocator]: Assertion '__first >= _M_ibegin() && __first <= __last && __last <= _M_iend()' failed.
Disallowed system call: SYS_kill
when I run it on http://codepad.org/KXgHqKS2.
Is there a problem with the logic of my function? If so, what is it, and is there a cleaner way to solve the problem?