Learning pathOriginal reference
Lesson 3 of 12

Iterators, edits, and invalidation

Use half-open ranges and reason about positions after structural changes.

end is a boundary, never an element

An iterator represents a position. For a nonempty vector, begin() identifies its first element; end() is one past its last. The half-open range [first, last) includes first and excludes last. begin() equals end() for an empty vector.

For 10 20 30 40 50, [begin() + 1, begin() + 4) contains 20 30 40. An endpoint may equal end(), but *end() is invalid. Both endpoints must belong to the same sequence, be in valid order, and remain within its permitted boundaries.

Insert before; erase an existing position

insert(position, x) places x before position, including insertion at end(). erase(position) removes one element; erase(first, last) removes a half-open range. erase(end()) is invalid, while erase(end(), end()) is a valid empty-range operation.

Insertion and erasure shift later logical indices. pop_back() removes the last element and returns no value: copy back() before removing when you need it afterward. Repeated front erasure can shift n(n − 1)/2 elements, making the total quadratic.

C++23
// Complete C++23 program. No input; output: 10 99 30
#include <iostream>
#include <vector>
int main() {
    std::vector<int> values{10, 20, 30};
    values.insert(values.begin() + 1, 99);
    values.erase(values.begin() + 2);
    for (int i = 0; i < static_cast<int>(values.size()); ++i) {
        if (i != 0) std::cout << ' ';
        std::cout << values[i];
    }
    std::cout << '\n';
}

Growth can move the elements

An append that reallocates may move all existing elements, so that individual append can cost O(n). Across n appends to an initially empty vector, append cost is O(n) amortized for fixed-cost elements. Amortized is a guarantee over a sequence, not a random-input average.

Reallocation invalidates saved iterators, pointers, and references to vector elements and the old end iterator. Even without reallocation, insertion invalidates handles at or after its position, and erasure invalidates handles at or after its position. Reacquire positions after a structural change when unsure.

Reserve does not make self-appending loops safe

A range-based loop remembers its boundaries. Appending invalidates the old end even when reserve prevents element relocation. Build a separate result vector, or deliberately snapshot the original length for an indexed loop and copy each needed value before appending.

An integer index does not dangle when storage moves, but insertion or erasure can make it identify a different logical item. Stable IDs should be stored as data; a current index is not a permanent identity.

Container workbench

Insert values, then remove the next accessible item. Priority queue values are shown sorted for explanation, not as an internal heap.

80
31
52

Next removal: 5. Size: 3.

Guided simulation · Change the inputs to test your understanding.

Pause & predict

Does reserving enough capacity make it generally safe to push_back into a vector during a range-based loop over that same vector?

Choose an answer
Try it yourself

Turn the idea into code

Trace a = 10 20 30 40 50 through reverse([1, 4)), insert 99 before index 2, then erase index 3. Give every intermediate sequence and explain which original value is erased.

Give me a hint

Use the current indices after every operation, not the original ones.

Show the explained solution

After reversal: 10 40 30 20 50. After insertion: 10 40 99 30 20 50. After erasing current index 3: 10 40 99 20 50. The erased value is 30. The insertion changed where later values lived.

Your notes

Ready for the next idea?

Mark complete when you can explain it yourself.

From a problem to a programIdentify the input, output, and constraints, then translate a small plan into C++.Variables, types, and remembered valuesChoose a representation, initialize it, and understand what assignment really changes.Arithmetic without surprisesPredict division and remainder, widen before multiplication, and format decimal answers.Conditions and logical decisionsBuild exclusive categories, combine comparisons, and protect operations with short-circuit logic.Optional: other ways to chooseRecognize switch for exact choices and the conditional operator for choosing a value.For loops: make repetition preciseTrace initialization, condition, body, and update—and avoid an extra iteration.While, do-while, and stopping rulesChoose a loop from its stopping condition and read the exact input format.Break, continue, and early answersDistinguish leaving a loop from skipping one iteration, without losing required input.Five patterns worth understandingUse sums, counts, best-so-far candidates, products, and flags to process a stream.Nested loops: rows and columnsTranslate a shape into two loop roles and count the total work.Take a number apart, one digit at a timeUse remainder and division to process decimal digits, including zero.Multiple cases and a debugging mindsetCombine the patterns, isolate each case, and test the boundaries that can break your idea.Arrays: give every value a placeUnderstand indices, initialization, capacity, active length, and the first safe array loop.Scan, count, search, and compareDistinguish values from positions and preserve the exact tie rule a problem asks for.Change a sequence without losing itUpdate, copy, compare, reverse, and inspect neighbours using the correct bounds.Matrices: think in two coordinatesTraverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.Characters become stringsSeparate characters from numbers, then safely inspect and edit managed text.Read the text the problem actually givesChoose words or full lines, preserve empty cases, and reset only the state that needs it.Scan text: count, filter, transformBuild a result from matching characters without losing leading zeros or skipping shifted text.Join, compare, and find textLearn content comparison, lexicographical order, substring counts, and the not-found sentinel.