Iterators generalize pointers—algorithms use begin() and end() to process containers uniformly.
Iterator loop
for (auto it = v.begin(); it != v.end(); ++it) {
std::cout << *it;
}
Range-for is syntactic sugar when you do not need the iterator itself. Watch iterator invalidation after vector reallocation or erase.
Important interview questions and answers
- Q: end() iterator?
A: One-past-last sentinel—not dereferenceable; marks range termination. - Q: const_iterator?
A: Read-only traversal without modifying elements.
Self-check
- What range do begin/end define?
- Why can vector iterators invalidate?
Pitfall: vector iterators invalidate on reallocation—do not store iterators across push_back without refreshing.
Interview prep
- end() iterator?
One-past-last sentinel—not dereferenceable; marks range termination.
- Iterator invalidation?
Certain container mutations (especially vector reallocation) invalidate iterators.