I'm using Visual Studio 2015 Update 1 C++ compiler and this code snippet:
#include <iostream> #include <vector> using namespace std; int main() { vector<int> v{3, 1, 4}; v.reserve(6); for (auto e: v) v.push_back(e*e); for (auto e: v) cout << e << " "; return 0; }
Release version runs fine, but debug version produces vector iterators incompatible
error message. Why is that?
Before you flag it as a duplicate question to Add elements to a vector during range-based loop c++11, please read my answer https://stackoverflow.com/a/35467831/219153 with arguments to the contrary.
According to documentation:
If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.
It says even if capacity is enough past-the-end iterator is invalidated, so I believe your code has undefined behavior (unless this documentation is incorrect and standard says otherwise)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With