【问题标题】:c++ map erase(), iterator printing erased elementc++ map erase(),迭代器打印擦除的元素
【发布时间】: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。你的例子就是这样做的。

标签: c++ stl


【解决方案1】:

迭代器 (it) 指向 mymap 中的特定内存地址。一旦调用 mymap.erase(it),该内存地址就不再存在于 mymap 中,因此迭代器变得无效并且在重新初始化之前不应访问。

在您的情况下,迭代器最终返回 0。但是,它可能很容易地返回 3、99、-244242 或任何其他已使用的不同内存存储。这就是为什么你永远不想在迭代器失效后访问它,因为它会导致未定义的行为。

it = mymap.find('b');
mymap.erase(it); 
std::cout << it->first  << " " << it->second << std::endl; // this is not allowed!!!

如果您需要在从 mymap 中删除该值后访问该值,则应先将其复制到变量中。

it = mymap.find('b');
std::pair<char, int> temp = *it;
mymap.erase(it);                   // erasing by iterator
std::cout << temp.first << " => " << temp.second << std::endl;

【讨论】:

    猜你喜欢
    • 2014-06-11
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多