【发布时间】:2018-04-21 13:40:00
【问题描述】:
为什么下面代码的输出是b 0:
int main ()
{
std::map<char,int> mymap;
std::map<char,int>::iterator it;
mymap['a']=10;
mymap['b']=20;
mymap['c']=30;
mymap['d']=40;
mymap['e']=50;
mymap['f']=60;
it=mymap.find('b');
mymap.erase (it); // erasing by iterator
std::cout << it->first << " " << it->second << std::endl;
mymap.erase ('c'); // erasing by key
it=mymap.find ('e');
mymap.erase ( it, mymap.end() ); // erasing by range
// show content:
for (it=mymap.begin(); it!=mymap.end(); ++it)
std::cout << it->first << " => " << it->second << '\n';
return 0;
}
【问题讨论】:
-
mymap.erase (it);此时it失效。 -
先生,您说的无效是什么意思?当我将 cout 移到 mymap.erase('c') 之后,它会打印 '0 0'
-
@CerealKiller 这意味着
it的当前值变得不可用。您不能像以前那样在cout行中使用它。 -
“无效”表示不应使用它的值,并且尝试使用它的程序显示undefined behavior。你的例子就是这样做的。