c++ - 在 for-each 循环中删除 vector 的一些元素而不迭代整个 vector

标签 c++ c++11 iterator

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

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

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

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

什么是这样做的好方法?

最佳答案

你还是应该使用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);

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

关于c++ - 在 for-each 循环中删除 vector 的一些元素而不迭代整个 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50079447/

相关文章:

c++ - cerr 未定义

c++ - 在 Linux Mint 17.1 64 位(未声明/不是类型)上尝试 "make"C++ 项目时从 cstdlib 编译错误和类似错误

c++ - 无限数组 C++ 在一个表达式中使用两个新值调整数组大小

c++ - 大类型的 const T& 和简单类型的 T 的特化模板

c++ - 将局部对象复制到 vector

java - 对值进行两次迭代 (MapReduce)

c++ - fstream给我错误的文件大小

c++ - 如何在非模板类中存储仿函数?

python - 在什么情况下你应该在 python 中实际使用生成器?

C++ 迭代器错误 "does not refer to a value"