如果你在从开始到结束迭代时在地图元素上调用erase()会发生什么? [英] What happens if you call erase() on a map element while iterating from begin to end?

查看:105
本文介绍了如果你在从开始到结束迭代时在地图元素上调用erase()会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我通过一个映射循环,并测试一个元素是否需要被删除。是否可以擦除元素并保持迭代,或者我需要收集另一个容器中的键,并执行第二个循环调用erase()?

In the following code I loop through a map and test if an element needs to be erased. Is it safe to erase the element and keep iterating or do I need to collect the keys in another container and do a second loop to call the erase()?

map<string, SerialdMsg::SerialFunction_t>::iterator pm_it;
for (pm_it = port_map.begin(); pm_it != port_map.end(); pm_it++)
{
    if (pm_it->second == delete_this_id) {
        port_map.erase(pm_it->first);
    }
}



更新:当然, http://stackoverflow.com/questions/52714/stl-vector-vs-map-erase\">读这个问题,我不认为会相关,但回答我的问题。

UPDATE: Of course, I then read this question which I didn't think would be related but answers my question.

推荐答案

C ++ 11



擦除已在所有容器类型中得到改进/保持一致。)

擦除方法现在返回下一个迭代器。

C++11

This has been fixed in C++11 (or erase has been improved/made consistent across all container types).
The erase method now returns the next iterator.

auto pm_it = port_map.begin();
while(pm_it != port_map.end())
{
    if (pm_it->second == delete_this_id)
    {
        pm_it = port_map.erase(pm_it);
    }
    else
    {
        ++pm_it;
    }
}



C ++ 03



删除地图中的元素不会使任何迭代器无效。

(除了被删除的元素上的迭代器)

C++03

Erasing elements in a map does not invalidate any iterators.
(apart from iterators on the element that was deleted)

实际插入或删除不会使任何迭代器无效:

Actually inserting or deleting does not invalidate any of the iterators:

也看到这个答案:

Mark Ransom技术

但您需要更新代码:

你的代码在调用erase后增加pm_it。

But you do need to update your code:
In your code you increment pm_it after calling erase. At this point it is too late and is already invalidated.

map<string, SerialdMsg::SerialFunction_t>::iterator pm_it = port_map.begin();
while(pm_it != port_map.end())
{
    if (pm_it->second == delete_this_id)
    {
        port_map.erase(pm_it++);  // Use iterator.
                                  // Note the post increment.
                                  // Increments the iterator but returns the
                                  // original value for use by erase 
    }
    else
    {
        ++pm_it;           // Can use pre-increment in this case
                           // To make sure you have the efficient version
    }
}

这篇关于如果你在从开始到结束迭代时在地图元素上调用erase()会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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