我有一个 vector ,我正在搜索其中的一个元素,同时使用 for-each 循环遍历该 vector 。如果我在搜索过程中发现任何无效元素,我想将它们从 vector 中删除。
基本上,我想做这样的事情:
for (auto el : vec) {
if (el == whatImLookingFor) {
return el;
} else if (isInvalid(el)) {
vec.erase(el);
}
}
我查看了一些其他问题,例如 this和 this ,但两者都推荐使用 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/