首页 > 解决方案 > 在 for-each 循环中擦除向量的一些元素而不迭代整个向量

问题描述

我有一个向量,我正在其中搜索一个元素,同时使用 for-each 循环遍历该向量。如果在搜索过程中发现任何无效元素,我想将它们从向量中删除。

基本上,我想做这样的事情:

for (auto el : vec) {
    if (el == whatImLookingFor) {
        return el;
    } else if (isInvalid(el)) {
        vec.erase(el);
    }
}

我查看了一些其他问题,例如thisthis,但都推荐使用std::remove_if. 这将遍历整个向量并删除所有无效元素,而不是仅在找到我正在寻找的元素之前进行迭代,然后忽略之后的任何元素。

什么是这样做的好方法?

标签: c++c++11iterator

解决方案


您仍然应该使用std::remove_if,只需std::find提前致电。

auto el = std::find(vec.begin(), vec.end(), whatImLookingFor);
auto p = std::remove_if(vec.begin(), el, isInvalid);

// returns the iterator, not the element itself.
// if the element is not found, el will be vec.end()
return vec.erase(p, el);

这通常比一次删除一个元素更有效。


推荐阅读