delete a specific entry in the map,but the iterator must point to the next element after the deletion [duplicate]

蹲街弑〆低调 提交于 2019-12-23 22:24:28

问题


Duplicate:

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

How to filter items from a stdmap

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


回答1:


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

myMap.erase(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.




回答2:


map<...>::iterator tmp(iter++);
map1.erase(tmp);



回答3:


Simple Answer:

map.erase(iter++);  // Post increment. Increments iterator,
                    // returns previous value for use in erase method

Asked and answered before:
What happens if you call erase on a map element while iterating from begin to end
How to filter items from a stdmap




回答4:


#include <boost/next_prior.hpp>

map<string,vector<string> >::iterator next = boost::next(itr);
map1.erase(iter);
iter = next;


来源:https://stackoverflow.com/questions/268898/delete-a-specific-entry-in-the-map-but-the-iterator-must-point-to-the-next-eleme

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!