删除地图中的特定条目,但迭代器必须指向删除后的下一个元素 [英] delete a specific entry in the map,but the iterator must point to the next element after the deletion

查看:108
本文介绍了删除地图中的特定条目,但迭代器必须指向删除后的下一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


What happens if you call erase on a map element while iterating from begin to end

如何从stdmap

我有一张地图 map1< string,vector< string>> ; 我有一个迭代器为这个地图itr。
我想删除由itr指向的地图中的条目。
我可以使用函数map1.erase(itr);在这行之后,迭代器itr变得无效。
根据我的项目中的要求,迭代器必须指向下一个元素。可以任何身体帮助我提前重申这个
th $ :)
santhosh

I have a map map1<string,vector<string>> i have a iterator for this map "itr". i want to delete the entry from this map which is pointed by "itr". i can use the function map1.erase(itr); after this line the iterator "itr" becomes invalid. as per my requirement in my project,the iterator must point to the next element. can any body help me regerding this thans in advance:) santhosh

推荐答案

增加迭代器,同时将其作为参数传递以进行擦除:

You can post-increment the iterator while passing it as argument to erase:

myMap.erase(itr++)

这样,擦除之前被 itr 指向的元素被删除,迭代器递增,以指向地图中的下一个元素。如果您在循环中执行此操作,请注意不要将迭代器递增两次。

This way, the element that was pointed by itr before the erase is deleted, and the iterator is incremented to point to the next element in the map. If you're doing this in a loop, beware not to increment the iterator twice.

另请参见这个答案来自类似的问题,或已经对这个问题

See also this answer from a similar question, or what has been responded to this question.

这篇关于删除地图中的特定条目,但迭代器必须指向删除后的下一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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