This code is not valid. Standard definition of operations on sequence containers (23.2.3 @ 4):
a.insert (p, i, j) - [...] pre: i and j are not iterators in.
Thus, your code invokes undefined behavior because it violates the precondition for the insert operation.
If instead of using insert you wrote a loop myvector.rbegin() + 1 from myvector.rbegin() + 1 to myvector.rend() -1 and called push_back for all values, your code would be right: this is because push_back only cancels vector iterators if redistribution is required , and your reserve call ensures that it is not.
In the general case, although there are some cases where changing the container when iterating over it is fine (for example, the loop described above), you should make sure that your iterators are not invalid in doing so. When this happens, it is specific to each container.
source share