std::set:使用迭代器导致内存冲突异常



我有下面的代码。代码不能在Visual Studio中工作。但在另一个编译器中,如onlinegdb.com,它工作得很好。输出">

#include <iostream>
#include <set>
using namespace std;
int main()
{
set <int> ms{1,2,3,4,5};
set <int>::iterator it;
int i = 0;
for (it = ms.begin(); it != ms.end(); ++it) {
if (i == 4)  {
ms.erase(it);               // I know if I want to remove the last element, I can just code "ms.erase(--ms.end())" without the need of a loop
// it = ms.erase(it);       // replacing the above link with this line doesn't work neither
}
i++;
}
for (auto x : ms) {
cout << x << " ";
}
return 0;
}

输出:

  • 如果在onlinegdb.com上运行:1 2 3 4
  • 如果在Visual Studio 2019上运行,错误Expression: cannot increment value-initialized map/set iterator

我认为当最后一个元素被移除时,迭代器it将被设置为end。这样循环就会中断。

谁能给我解释一下为什么东西不能在Visual Studio工作?非常感谢。

必须使用erase函数返回什么。

如果你擦除,你应该而不是增加迭代器。

删除元素将使迭代器失效。使用从erase返回的迭代器是正确的做法,但该迭代器引用的元素在被擦除的元素后面,因此只有在不擦除时才应该自增:

for (it = ms.begin(); it != ms.end(); ) {   // do not increment here
if (i == 4)  {            
it = ms.erase(it);
} else {
++it;                               // but only when you do not erase
}
++i;
}

有关迭代器失效的详细信息,请参阅c++容器的迭代器失效规则。

最新更新