I have below code. The code doesn't work in Visual Studio. But in another compiler, such as onlinegdb.com, it works fine. And output "
#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;
}
Output:
- If run on onlinegdb.com:
1 2 3 4
- If run on Visual Studio 2019, error
Expression: cannot increment value-initialized map/set iterator
I think when the last element is removed, iterator it
will be set as end
. So the loop will break.
Can anyone explain for me why stuff cannot work in Visual Studio? Thank you so much.