remove_if 的 C++ 意外行为

C++ Unexpected behavior with remove_if

我正在尝试使用 std::remove_if 从一个简单的字符串中删除 spaces,但我得到了奇怪的结果。谁能帮我弄清楚这是怎么回事?

密码是:

#include <iostream>
#include <algorithm>
#include <string>

int main(int argc, char * argv[])
{
    std::string test = "a b";
    std::remove_if(test.begin(), test.end(), isspace);
    std::cout << "test : " << test << std::endl; 

    return 0;
}

我希望这可以简单地打印出来:

test : ab

但我得到

test : abb

尝试使用另一个字符串,我得到:

输入:"a bcde uv xy"

输出:"abcdeuvxy xy"

它似乎复制了最后一个 "word",但有时会添加一个 space。我怎样才能让它删除所有 space 而不做奇怪的事情?

std::remove_if通过移动元素执行移除removed 元素实际上不会从容器中erased。 STL算法没有这样的特权;只有容器可以删除它们的元素。

(强调我的)

Removing is done by shifting (by means of move assignment) the elements in the range in such a way that the elements that are not to be removed appear in the beginning of the range. Relative order of the elements that remain is preserved and the physical size of the container is unchanged. Iterators pointing to an element between the new logical end and the physical end of the range are still dereferenceable, but the elements themselves have unspecified values (as per MoveAssignable post-condition). A call to remove is typically followed by a call to a container's erase method, which erases the unspecified values and reduces the physical size of the container to match its new logical size.

您可以 erase 之后 删除 个元素(这被称为 erase–remove idiom)。

test.erase(std::remove_if(test.begin(), test.end(), isspace), test.end());