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

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

问题描述

据称,您不能在迭代时擦除/删除容器中的元素,因为迭代器变得无效.删除满足特定条件的元素的(安全)方法是什么?请只使用 stl,不要使用 boost 或 tr1.

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.

编辑如果我想擦除一些满足特定条件的元素,是否有更优雅的方法,也许使用函子和 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天全站免登陆