迭代器失效中的boost :: unordered_map [英] Iterator invalidation in boost::unordered_map

查看:554
本文介绍了迭代器失效中的boost :: unordered_map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的boost :: unordered_map 如下:

 的typedef的boost :: shared_ptr的< WriterExeciter> PtrWriter;
的typedef的std ::名单< PtrWriter> PtrList;
提高:: unordered_map<的std ::对<无符号整型,无符号长长>中PtrList>地图
地图instrMap;

现在我在一个循环中作出一些改变,以键入 PtrList 列表

 为(自动它= instrMap.begin();它= instrMap.end(!); ++吧)
{
     自动键=它 - >首先();
     自动列表和放大器; = IT->第二个();
     //进行一些更改列表中的一个元素      如果(list.empty())
      {
            instMap.erase(键);
      }}


  1. 请问在更改列表无效迭代器instrMap?


  2. 删除元素会作废指向被删除元素的迭代器。如何修改我的code,使这不会导致什么问题?是否使用它++ 而不是 ++的它帮助?


感谢


解决方案

擦除()操作将无效迭代器。然而,它也返回一个有效的迭代器的下一个元素。所以,你可以使用类似以下内容:

 为(自动它= instrMap.begin();它= instrMap.end();!)
{
     自动键=它 - >首先();
     自动列表和放大器; = IT->第二个();
     //进行一些更改列表中的一个元素      如果(list.empty())
      {
            它= instMap.erase(它);
      }
      其他{
            ++它;
      }
}

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

解决方案

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

这篇关于迭代器失效中的boost :: unordered_map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆