c++ - 如何在 std::remove_if 之后使用 "removed"元素

标签 c++ stl

假设我们有:

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_endV.end() 的元素不是我们要删除的偶数。例如,如果 v1 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/

相关文章:

c++ - Open_GL 中的透视问题

c++ - 如何通过引用返回对象?

c++ - std::transform 中的输入迭代器和输出迭代器来自同一个容器是否安全?

c++ - SIGILL 在 ideone 上运行,但在 Codeblocks 上运行时出现警告

c++ - 具有不同 const 正确性的 vector 的赋值运算符

c++ - 从函数返回 STL 对象而不触发 move

c++ - 使用 OpenSceneGraph 加载 DirectX 模型文件

c++ - sqlite CREATE INDEX exec 返回错误

c++ - --it 和 it-- 在

c++ - 并发 STL it++ 和 *it 安全吗?