以下内容
#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;
}
正在产生错误
/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
当我在 http://codepad.org/KXgHqKS2 上运行它时.
我的功能逻辑有问题吗?如果是,它是什么,是否有更简洁的方法来解决问题?
最佳答案
Is there a problem with the logic of my function?
是的,删除元素会使迭代器失效。如果您想通过 Steam 执行此操作,则需要进行两项更改:
- 不要在迭代之间存储
end
迭代器,或者删除后更新它; - 删除后更新
it
,it = erase(temp, it)
Is there a cleaner way to solve the problem?
s.erase(std::unique(s.begin(), s.end()), s.end());
关于c++ - 错误 "Disallowed system call: SYS_kill",因为我尝试从字符串中删除所有连续的重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29750312/