c++ - 在 for-each 循环中擦除向量的一些元素而不迭代整个向量
问题描述
我有一个向量,我正在其中搜索一个元素,同时使用 for-each 循环遍历该向量。如果在搜索过程中发现任何无效元素,我想将它们从向量中删除。
基本上,我想做这样的事情:
for (auto el : vec) {
if (el == whatImLookingFor) {
return el;
} else if (isInvalid(el)) {
vec.erase(el);
}
}
我查看了一些其他问题,例如this和this,但都推荐使用std::remove_if
. 这将遍历整个向量并删除所有无效元素,而不是仅在找到我正在寻找的元素之前进行迭代,然后忽略之后的任何元素。
什么是这样做的好方法?
解决方案
您仍然应该使用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);
这通常比一次删除一个元素更有效。
推荐阅读
- python - 创建命令说嵌入到 discord.py
- r - 根据 R 中的另一列对一列求和,但跳过带有 NA 的行
- java - 应用程序崩溃与 android 材料芯片组与材料 1.3.0
- http - 当 QUIC、HTTP/3 是预期的主要/所有流量时,HTTP 客户端连接池是否仍然有效?
- python - AES 无法正确解密
- javascript - 通过 Translate 与 Clipping 平移图像的 HTML5 Canvas 效率
- python - 来自 np.where 的 Python ValueError 基于一个条件创建标志
- python - 在没有 GPU 支持的情况下处理遗留的 tensorflow
- c++ - 没有这样的文件或目录
- html - Angular HTML 中括号 [] 和没有括号有什么区别?