c ++设置擦除函数无法与迭代器一起正常工作

c++ set erase function not working properly with iterator

set<int> s = {1, 2, 3, 4};
auto it = s.begin();
while (it != s.end()) {
    // this correct 
    s.erase(it++);
    
    // this incorrect 
    s.erase(it);
    it++;
}

为什么在代码之上可以运行?

当我的代码 运行 时我对顺序的理解是:

  1. 执行擦除函数时,迭代器被删除。
  2. 执行 add 的混乱迭代器,其行为未定义。

但是运行正常,所以我的问题是为什么运行和这些代码有区别?

最好的方法是:

it = s.erase(it);

带有 post-increment 的代码也可以工作,但不太透明。回想一下,post-增量版本在语义上等同于以下代码段:

temp = it;
++it;
s.erase(temp);

至于您声称的格式错误(第二版)代码“运行”,具有未定义行为的代码可能是“运行”,甚至似乎提供了预期的结果。这是未定义行为的要点。根据 std::set::erase documentation:

,递增已被擦除的迭代器的代码表现出未定义的行为

References and iterators to the erased elements are invalidated. Other references and iterators are not affected