编辑:std::remove的文档已经修复,因为这个答案是写的。同样的事情也适用于list::remove。
让我给你一个例子来说明cpluscplus.com是如何出错的。
考虑std::remove函数从<算法>。
The fact is thatstd::remove doesn't remove the item from the container. Its because std::remove works with a pair of iterators only and does not know anything about the container which actually contains the items. In fact, it's not possible for std::remove to know the underlying container, because there is no way it can go from a pair of iterators to discover about the container to which the iterators belong. So std::remove doesn't really remove the items, simply because it cannot. The only way to actually remove an item from a container is to invoke a member function on that container.
所以如果你想删除项目,那么使用擦除-删除习语:
v.erase(std::remove(v.begin(), v.end(), 10), v.end());
但是cplusplus.com给出了关于std::remove的错误信息。它说
注意,这个函数不会改变new结束后的元素,这些元素保持旧值,仍然可以访问。
这是不正确的。[new_end, old_end)范围内的迭代器仍然是可解引用的,但这并不意味着它们保持旧值并且仍然可以访问。他们没有具体说明。
类似地,cplusplus.com也给出了关于list::remove的错误信息。它说,
请注意,存在一个全局算法函数remove,其行为类似,但操作在两个迭代器之间。
这是完全错误的。全局remove(即std::remove)与list::remove不相似,正如我们所看到的,前者不会真正从容器中删除项,因为它不能,而后者(成员函数)确实会删除项,因为它可以。
这个答案是从我在以下主题的另一个答案中复制过来的,有一点修改:
STL删除不像预期的那样工作?
注:因为我最近在回复上面的话题时遇到了这个问题,所以我记得它。在过去的两年里,我遇到了很多错误,我不记得了。如果以后再遇到的话,我可能会再补充一些。