简体   繁体   English

boost :: unordered_map中的迭代器无效

[英]Iterator invalidation in boost::unordered_map

I am using boost::unordered_map as follows 我正在使用boost::unordered_map如下

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 现在,我在循环中对PtrList类型的列表进行了一些更改

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? 更改列表是否会使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? 使用it++代替++it帮助吗?

Thanks 谢谢

The erase() operation will invalidate the iterator. erase()操作将使迭代器无效。 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;
      }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM