迭代时从地图(或任何其他STL容器)中擦除/删除内容 [英] Erase/Remove contents from the map (or any other STL container) while iterating it

查看:65
本文介绍了迭代时从地图(或任何其他STL容器)中擦除/删除内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据称,当迭代器变为无效时,您不能在进行迭代时仅擦除/删除容器中的元素。删除满足特定条件的元素的(安全)方法是什么?

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.

编辑
如果我想删除一些满足特定条件的元素,也许使用functor和for_each或擦除算法?

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 ?

推荐答案

bool IsOdd( int i )
{
    return (i&1)!=0;
}

int a[] = {1,2,3,4,5};
vector<int> v( a, a + 5 );
v.erase( remove_if( v.begin(), v.end(), bind1st( equal_to<int>(), 4 ) ), v.end() );
// v contains {1,2,3,5}
v.erase( remove_if( v.begin(), v.end(), IsOdd ), v.end() );
// v contains {2}

这篇关于迭代时从地图(或任何其他STL容器)中擦除/删除内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆