Problem with std::map::iterator after calling erase()(调用 erase() 后 std::map::iterator 出现问题)
问题描述
// erasing from map
#include <iostream>
#include <map>
using namespace std;
int main ()
{
map<char,int> mymap;
map<char,int>::iterator it(mymap.begin());
// insert some values:
mymap['a']=10;
mymap['b']=20;
mymap['c']=30;
mymap['d']=40;
mymap['e']=50;
mymap['f']=60;
it=mymap.find('a');
mymap.erase (it); // erasing by iterator
// show content:
for (; it != mymap.end(); it++ )
cout << (*it).first << " => " << (*it).second << endl;
return 0;
}
为什么会给出这样的输出
Why does this give an output like
a => 10
b => 20
c => 30
d => 40
e => 50
f => 60
无论如何都不应该删除 "a => 10" ,但是如果我在 for 循环中声明 it = mymap.begin() ,一切都很完美.为什么?
shouldn't "a => 10" be deleted anyways, but if I declare it = mymap.begin() in the for loop, everything is perfect. why?
程序改编自:http://www.cplusplus.com/reference/stl/map/erase/
推荐答案
擦除 map 的元素会使指向该元素的迭代器无效(在所有该元素都被删除之后).您不应该重复使用该迭代器.
Erasing an element of a map invalidates iterators pointing to that element (after all that element has been deleted). You shouldn't reuse that iterator.
C++11起erase()返回一个指向下一个元素的新迭代器,可以用来继续迭代:
Since C++11 erase() returns a new iterator pointing to the next element, which can be used to continue iterating:
it = mymap.begin();
while (it != mymap.end()) {
if (something)
it = mymap.erase(it);
else
it++;
}
在 C++11 之前,您必须在删除发生之前手动将迭代器前进到下一个元素,例如:
Before C++11 you would have to manually advance the iterator to the next element before the deletion takes place, for example like this:
mymap.erase(it++);
这是因为 it++ 的后增量副作用发生在 erase() 删除元素之前.由于这可能不是很明显,因此应该首选上面的 C++11 变体.
This works because the post-increment side-effect of it++ happens before erase() deletes the element. Since this is maybe not immediately obvious, the C++11 variant above should be preferred.
这篇关于调用 erase() 后 std::map::iterator 出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:调用 erase() 后 std::map::iterator 出现问题
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
