Iterator invalidation in boost::unordered_map

浪子不回头ぞ 提交于 2019-12-01 04:56:00

问题


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


回答1:


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;
      }
}


来源:https://stackoverflow.com/questions/11443405/iterator-invalidation-in-boostunordered-map

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