Iterator Invalidity in boost :: unordered_map

I use boost::unordered_map as follows

 typedef boost::shared_ptr<WriterExeciter> PtrWriter; typedef std::list<PtrWriter> PtrList; boost::unordered_map<std::pair<unsigned int, unsigned long long>, PtrList> Map Map instrMap; 

Now I am making some changes to a list of type PtrList in a loop

 for(auto it = instrMap.begin(); it != instrMap.end(); ++it) { auto key = it->first(); auto list& = it->second(); //Make some change to an element in list if(list.empty()) { instMap.erase(key); } } 
  • Does making changes to the list invalidate the iterator for instrMap?

  • Erasing an element will invalidate the iterator that points to the erased element. How can I change the code so that it does not cause any problems? Does it++ instead of ++it help?

thanks

+4
source share
1 answer

The erase() operation will invalidate the iterator. However, it also returns a valid iterator for the next element. So you can use something like the following:

 for(auto it = instrMap.begin(); it != instrMap.end();) { auto key = it->first(); auto list& = it->second(); //Make some change to an element in list if(list.empty()) { it = instMap.erase(it); } else { ++it; } } 
+5
source

All Articles