Explain iterator invalidation. Give an example of an operation that invalidates a std::vector iterator.

Last updated 21 June 2026

  • Iterator invalidation: a container modification leaves existing iterators, pointers, or references dangling, and using them is undefined behavior.

  • For std::vector, a push_back() exceeding capacity() reallocates and invalidates all iterators. insert()/erase() invalidate those at and after the change point.

  • Safe idiom: it = v.erase(it). Node-based containers like std::list keep other iterators valid.

  • https://utkrusht.ai/blog/cplusplus-interview-questions
  • https://roadmap.sh/questions/cpp
  • https://internshala.com/blog/cpp-coding-interview-questions/
All C++ interview questions