What you observe is the details of specific implementation you are dealing with (i.e. this is how your application works on specific platform built by specific version of the compiler). However C++ is the language which is implemented based on so-called standard. This document describes contract of what the implementation must maintain for every version of the language. You didn't specify which language version you use, but if you refer to draft n4861 (C++ 20), you can find that it requires any iterator which points at of after position of the inserted element to be invalidated (vector.modifiers/1, emphasis mine):
Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence, as well as the past-the-end iterator. If no reallocation happens, then references, pointers, and iterators before the insertion point remain valid but those at or after the insertion point, including the past-the-end iterator, are invalidated.
This is self-explanatory on its own, but the standard even defines what it means to dereference such an iterator in the footnote of iterator.requirements.general:
...The effect of dereferencing an iterator that has been invalidated is undefined.
The "undefined" is not an abstract term in the standard. It essentially means, that the compiler vendors are free to implement whatever they want in this scenario, even if it's counter-intuitive to the programmer (this freedom, however, helps to introduce optimization to the program). So if you have a program with undefined behavior, it means you cannot reliably know how it will work (and whether it will work at all) in any other versions of the compiler (even from the same vendor) or other platforms.
#include <bits/stdc++.h>. Tread cautiously on that site. Lot of BS floating around on Geeks For Geeks.v.capacity() > v.size()after the fact is not a good check for "vector has not been re-allocated". It is very likely thatv.capacity() > v.size()immediately after a reallocation.insertcan never trigger a reallocation and will always be after outstanding iterators, assume that any insert will invalidate iterators. If you simply assume that it can't resize, sooner or later you'll have to fix a bug.if(v.capacity() > v.size()) {offers no protection, and actually offers a false sense of security. For any vector (assuming no undefined behaviour has occurred)v.capacity() >= v.size()will always be true. Your test only checks ifv.capacity() > v.size()is true AFTER doing theinsertoperation. Whereas, theinsertoperation avoids resizing ONLY if the originalv.capacity()(BEFORE inserting) is not less than the new size (AFTER inserting).