Explain iterator invalidation. Give an example of an operation that invalidates a std::vector iterator.
Last updated
Iterator invalidation: a container modification leaves existing iterators, pointers, or references dangling, and using them is undefined behavior.
For
std::vector, apush_back()exceedingcapacity()reallocates and invalidates all iterators.insert()/erase()invalidate those at and after the change point.Safe idiom:
it = v.erase(it). Node-based containers likestd::listkeep other iterators valid.