简体   繁体   English

迭代时擦除std :: map的其他元素

[英]Erase other elements of std::map while iterating

I have a map with following key value pairs. 我有一个包含以下键值对的地图。 {(a,P),(b,Q),(c,R),(d,S),...(g,Z)} {(a,P),(b,Q),(c,R),(d,S),...(g,Z)}

I'm iterating this map and at each element I take a branch which access this same map and erase an element of the map if a condition is met. 我正在迭代此地图,并且在每个元素处我都取得了一个分支,该分支访问相同的地图,并在满足条件时擦除该地图的元素。 Simply put, it is possible that while the main iterator is at (bQ) , the branching function can erase (d,S). 简而言之,当主迭代器位于(bQ)时,分支功能可能会擦除(d,S)。

Is this valid.? 这有效吗? Or will this seg fault.? 还是这段错误?

You need to read the iterator invalidation rules: 您需要阅读迭代器失效规则:

std::map::erase std :: map :: erase

References and iterators to the erased elements are invalidated. 对已删除元素的引用和迭代器无效。 Other references and iterators are not affected. 其他引用和迭代器不受影响。

So as long as you don't use the iterator where you erased, you are good. 因此,只要您不在擦除的地方使用迭代器,就可以了。

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

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