4

I am using 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 the 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); 
      }



}
  1. Does making changes to the list invalidate the iterator to instrMap?

  2. Erasing the element will invalidate the iterator pointing to the erased element. How do I modify my code so that the this does not cause any problem? Does using it++ instead of ++it help?

Thanks

bisarch
  • 1,388
  • 15
  • 31

1 Answers1

5

The erase() operation will invalidate the iterator. However, it also returns a valid iterator to 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;
      }
}
Michael Burr
  • 333,147
  • 50
  • 533
  • 760
  • I looked into the documentation. It should be instMap.erase(it) instead of instMap.erase(key). The second expression returns the number of elements erased. – bisarch Jul 12 '12 at 16:06
  • @sank: you're right - that was a careless copy/paste error. Fixed. – Michael Burr Jul 12 '12 at 16:26