删除元素时映射迭代器如何失效?
使用擦除方法时,迭代器何时以及如何在映射中失效?
例如:
std :: map < int , int > aMap ;
aMap [ 33 ] = 1 ;
aMap [ 42 ] = 10000 ;
aMap [ 69 ] = 100 ;
aMap [ 666 ] = -1 ;
std :: map < int , int > :: iterator itEnd = aMap.lower_bound ( 50 ) ;
for ( std :: map < int , int > :: iterator it = aMap.begin ( ) ;
it != itEnd ;
// no-op
)
{
aMap.erase ( it ++ ) ;
}
被擦除的迭代器肯定会变得无效(它在仍然有效的同时递增) 但其他人呢?
如果我没有错,标准说映射必须是平衡二叉树或具有等效键搜索复杂性的结构
,如果映射是用树实现的,我可以假设未擦除的迭代器仍然有效吗?
实现地图的其他可能方法怎么样?
when and how are iterators invalidated in a map when using the erase method ?
for example :
std :: map < int , int > aMap ;
aMap [ 33 ] = 1 ;
aMap [ 42 ] = 10000 ;
aMap [ 69 ] = 100 ;
aMap [ 666 ] = -1 ;
std :: map < int , int > :: iterator itEnd = aMap.lower_bound ( 50 ) ;
for ( std :: map < int , int > :: iterator it = aMap.begin ( ) ;
it != itEnd ;
// no-op
)
{
aMap.erase ( it ++ ) ;
}
the erased iterator will surely become invalid (it's incremented while still valid)
but what about the others?
if I'm not wrong the standard says that a map has to be a balanced binary tree or a structure with equivalent key-search complexity
in case the map is implemented with a tree, can I assume that not erased iterators remain valid ?
what about other possible ways to implement a map ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
continue
Only the erased iterator is invalid, the rest are guaranteed by the standard to remain valid.
See Iterator invalidation rules
If the map were to be implemented as a balanced tree, after doing erase, the tree might need to be rebalanced, that means that the positions an iterator was pointing to, could now have something else or nothing there, depending on the rebalancing of the tree, so that's why that iterator is invalidated when you remove an element from the map, having erased the element, the iterator now ends up pointing at some memory that is no longer valid, which is 不明确的 Behaviour.
What if you decide to remove all elements from the map, inside your loop, what are the iterators gonna end pointing at?
If the map were to be implemented as a balanced tree, after doing erase, the tree might need to be rebalanced, that means that the positions an iterator was pointing to, could now have something else or nothing there, depending on the rebalancing of the tree, so that's why that iterator is invalidated when you remove an element from the map, having erased the element, the iterator now ends up pointing at some memory that is no longer valid, which is Undefined Behaviour.
What if you decide to remove all elements from the map, inside your loop, what are the iterators gonna end pointing at?