How do vector::reserve and vector::resize differ in size, capacity, construction, and iterator invalidation?
Show answer and explanation
reserve requests capacity for at least a number of elements without changing size or constructing elements. If it grows capacity, reallocation invalidates all iterators, pointers, and references; a request not exceeding current capacity has no effect. resize changes the number of elements, constructing appended values or destroying removed ones. Growth invalidates every handle if it reallocates, otherwise existing element handles remain valid but the old past-the-end iterator does not; shrinking invalidates handles to erased elements and the past-the-end iterator. Reserve before known push operations to reduce reallocations, but never index capacity beyond size; shrink_to_fit remains a non-binding request.
reserve requests capacity for at least a number of elements without changing size or constructing elements. If it grows capacity, reallocation invalidates all iterators, pointers, and references; a request not exceeding current capacity has no effect. resize changes the number of elements, constructing appended values or destroying removed ones. Growth invalidates every handle if it reallocates, otherwise existing element handles remain valid but the old past-the-end iterator does not; shrinking invalidates handles to erased elements and the past-the-end iterator. Reserve before known push operations to reduce reallocations, but never index capacity beyond size; shrink_to_fit remains a non-binding request.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.