迭代器失效中的boost :: unordered_map [英] Iterator invalidation in 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(键);
}}
-
请问在更改列表无效迭代器instrMap?
-
删除元素会作废指向被删除元素的迭代器。如何修改我的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);
}
}
Does making changes to the list invalidate the iterator to instrMap?
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屋!