假设我们有:
struct IsEven {
bool operator() (int i) { return i % 2 == 0; }
};
然后:
vector<int> V; // fill with ints
vector<int>::iterator new_end = remove_if(V.begin(), V.end(), IsEven());
V.erase(new_end, V.end());
工作正常(它只留下 V
奇数)。但似乎从 new_end
到 V.end()
的元素不是我们要删除的偶数。例如,如果 v
以 1 4 2 8 5 7
开始,那么我将得到这些元素的 8 5 7
(尽管在erase
调用, vector 确实还剩下 1 5 7
)。
显然,(根据 http://www.sgi.com/tech/stl/remove_if.html )
The iterators in the range [new_last, last) are all still dereferenceable,
but the elements that they point to are unspecified.
首先,WTF?其次,如何在不重新实现 remove_if
的情况下解决这个问题?
最佳答案
听起来您想使用 partition()
将 vector 划分为开始时的奇数组和结束时的偶数组。 partition()
将返回指向第二个分组的第一个元素的迭代器。
至于 WTF,我不确定为什么您会期望删除操作通过将要删除的元素复制(这是额外的工作)到容器的末尾来保留它们。
大多数人认为 remove()
(及其同类)中的 WTF 是 vector 的大小没有减少的事实,您必须调用 erase()
来实际上在删除操作后删除不需要的元素。
关于c++ - 如何在 std::remove_if 之后使用 "removed"元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/477331/