c++ - 错误 "Disallowed system call: SYS_kill",因为我尝试从字符串中删除所有连续的重复元素

标签 c++ string algorithm

以下内容

#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迭代器,或者删除后更新它;
  • 删除后更新itit = 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/

相关文章:

java - 以C/C++和其他语言重现Java原语hashCode逻辑的库

c++ - 构建 libuv 时 undefined symbol

c# - 从静态函数访问外部变量

c - HackerRank 上的对角线差异

javascript - 你如何比较两个函数在 Javascript 中的行为是否相同?

C++ 随机数仅在打印出值时导致崩溃。很奇怪

c++ - 如何将c++实验库添加到mac编译器?

java - JVM 在共享字符串数据方面可以更聪明吗?

javascript - 如何在 Javascript 中动态删除字符串中的多余空间?

algorithm - 如何按字典顺序枚举无序的整数对