问题std :: map :: iterator后调用erase() [英] Problem with std::map::iterator after calling erase()

查看:112
本文介绍了问题std :: map :: iterator后调用erase()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// 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;
}

为什么这样输出

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. Instead, advance the iterator to the next element before the deletion takes place, for example like this:

mymap.erase(it++);

删除某些元素的循环可能如下所示:

A loop deleting some elements could look like this:

it = mymap.begin();
while (it != mymap.end()) {
   if (something)
      mymap.erase(it++);
   else
      it++;
}

这篇关于问题std :: map :: iterator后调用erase()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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