Why does the same code run differently in Visual Studio and Dev
This question already has an answer here:
This is due to undefined behavior when you use the iterator after the call to v.assign()
as assign invalidates iterators and so using an iterator after that call is a bad idea.
Interestingly VS does reuse the same underlying memory after the call to assign (its still got the same address with capacity 10 but new size of 3) but its got a feature called Debug Iterators. When this feature is on, as it is by default for a Debug build, it stores a list of valid iterators and so knows that your iterator has been invalidated and tells you nicely. In a faster Release build it doesn't run these checks so it has undefined behavior but happens to print out the right values.
A compiler with less sophisticated iterator debugging machinery wont do this and you get undefined behavior (which manifests itself in the most scary way - by doing exactly what you expect)
If you happened to store a pointer to the first element then even Debug Iterators wont help you are you'll probably get the value you expect printed but its still undefined behavior!
链接地址: http://www.djcxy.com/p/73346.html上一篇: 在下列情况下,迭代器何时失效