tags:

views:

794

answers:

4

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

+2  A: 
map<...>::iterator tmp(iter++);
map1.erase(tmp);
Igor Semenov
A: 
#include <boost/next_prior.hpp>

map<string,vector<string> >::iterator next = boost::next(itr);
map1.erase(iter);
iter = next;
Leon Timmermans
+4  A: 

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.

Luc Touraille
+1  A: 

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

Martin York