在迭代时从地图(或任何其他 STL 容器)中擦除/删除内容

2022-01-07 00:00:00 c++ 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}

相关文章