删除元素时映射迭代器如何失效?

发布于 2024-12-03 11:36:13 字数 558 浏览 2 评论 0原文

使用擦除方法时,迭代器何时以及如何在映射中失效?

例如:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

何必那么矫情 2024-12-10 11:36:13

continue

Only the erased iterator is invalid, the rest are guaranteed by the standard to remain valid.

See Iterator invalidation rules

醉城メ夜风 2024-12-10 11:36:13

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文