Erase/Remove contents from the map (or any other STL container) while iterating it(在迭代时从地图(或任何其他 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 容器)中擦除/删除内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在迭代时从地图(或任何其他 STL 容器)中擦除/删除内容
基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
