What happens if you call erase() on a map element while iterating from begin to end?(如果在从头到尾迭代时在地图元素上调用 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);
}
}
更新:当然,然后我阅读了这个问题,但我没有认为是相关的,但回答了我的问题.
UPDATE: Of course, I then read this question which I didn't think would be related but answers my question.
推荐答案
C++11
这已在 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:
另请参阅此答案:
标记赎金技术
但您确实需要更新您的代码:
在您的代码中,您在调用擦除后增加 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() 会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果在从头到尾迭代时在地图元素上调用 erase() 会发生什么?
基础教程推荐
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 设计字符串本地化的最佳方法 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01