迭代时从地图(或任何其他 STL 容器)中擦除/删除内容
据称,当迭代器变得无效时,您不能在迭代时删除/删除容器中的元素。 删除满足特定条件的元素的(安全)方法是什么? 请只使用 stl,不要使用 boost 或 tr1。
编辑 如果我想删除满足特定条件的多个元素,是否有更优雅的方法,也许使用函子和 for_each 或擦除算法?
Allegedly you cannot just erase/remove an element in a container while iterating as iterator becomes invalid. What are the (safe) ways to remove the elements that meet a certain condition? please only stl, no boost or tr1.
EDIT
Is there a more elegant way if I want to erase a number of elements that meet a certain criteria, perhaps with using functor and for_each or erase algorithm ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
只要在擦除迭代器后不使其无效即可:
You can as long as you don't invalidate your iterator after you've erased it:
std::vector 的示例
Example with std::vector
Viktor 的解决方案的优点是能够在删除之前对元素执行某些操作。 (我无法使用
remove_if
或remove_copy_if
执行此操作。)但我更喜欢使用std::find_if
所以我永远不必自己增加迭代器:其中 Predicate 可以是
bind1st( equal_to(), 4 )
或类似这样的内容:Viktor's solution has the upside of being able to do something with the element before removing. (I wasn't able to do this with
remove_if
orremove_copy_if
.) But I prefer to usestd::find_if
so I never have to increment the iterator myself:Where Predicate could be
bind1st( equal_to<int>(), 4 )
or something like this:我更喜欢带有
while
的版本:使用
while
时,不会像for
中那样将it
增加两倍环形。I prefer version with
while
:With
while
there is no danger to incrementit
twice as it could be infor
loop.1.对于
std::vector<>
:2.对于
std::map<>
始终使用std::map::erase()< /code>
std::list
使用std::list::erase()
1.For
std::vector<>
:2.For
std::map<>
always usestd::map::erase()
std::list
usestd::list::erase()
markh44 是最 STL 风格的响应。
但请注意,一般情况下,迭代器会因修改容器而失效,但 set 和 map 除外。 在那里,您可以删除项目并继续使用迭代器,除非您删除迭代器正在引用的项目。
markh44 is the most STL-ish response.
Note, however, that in general, iterators are invalidated by modifying the container, but set and map are exceptions. There, you can remove items and still go on using the iterators, except if you delete the very item your iterator is referencing.
利用后递减运算符在递减之前返回迭代器的副本这一事实。 由于递减迭代器在擦除当前元素后仍然有效,因此 for 循环继续按预期运行。
编辑:如果您尝试删除列表中的第一个元素,则不起作用......
Use the fact that the post-decrement operator returns a copy of the iterator before it decrements. Since the decremented iterator is still valid after erasing the current element, the for loop continues to operate as intended.
Edit: Doesn't work if you attempt to erase the first element in the list....