【问题标题】:C++ Erase not working as expected [duplicate]C ++擦除未按预期工作[重复]
【发布时间】:2016-06-02 22:54:29
【问题描述】:

考虑以下程序:

#include <iostream>
#include <string>
#include <algorithm>    // std::remove

int main ()
{
  std::string str ("This is   an   example sentence blah");
  std::remove(str.begin(), str.end(), '\t');
  std::cout << str ;
  return 0;

}

(is,an) 和 (an,example) 之间有一个制表符,其他是空格。

我预计输出是:

这是一个例句等等

相反,我得到以下输出:

This is an example sentence blahah

额外的“ah”是否存在缓冲区溢出?

更多: 经过几次运行后,我注意到末尾的尾随字母数量与被删除的标签数量成正比。在这种情况下,字符串中有 2 个制表符,因此有 2 个额外的尾随字符。我可以通过使用擦除来处理它,但是为什么会发生呢?我不确定这是设计缺陷还是我遗漏了什么?

【问题讨论】:

  • 你试过阅读std::remove的文档吗?
  • 改变你的期望。

标签: c++


【解决方案1】:

是的,您错过了 std::remove 的事实,正如任何文档中所指出的那样,实际上并没有从容器中删除元素。

当找到要删除的元素时,将其后的元素移向容器的开头(通过移动赋值operator=(T&amp;&amp;))并返回一个指向容器新端的迭代器,但容器本身是不受影响。

所以要真正从容器中移除它们,你应该这样做:

auto it = std::remove(...);
container.erase(it, container.end());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 2018-08-26
    • 1970-01-01
    相关资源
    最近更新 更多