std::vector<T> · C++

insert / emplace

Inserts before pos, shifting later elements right.

iterator insert(const_iterator pos, const T& value); template<class... Args> iterator emplace(const_iterator pos, Args&&... args);

Complexity

Best caseO(1) at end()
Worst caseO(n)
Extra spaceO(1) amortized

Linear in the number of elements between pos and end(), which are moved one slot right.

Tested example

std::vector<std::string> v{"a", "c", "d"};
auto it = v.insert(v.begin() + 1, "b");  // shifts "c" and "d" right
assert(*it == "b");
assert((v == std::vector<std::string>{"a", "b", "c", "d"}));
// `it` and every iterator at or after the insertion point may now be invalid
Runs in the test suite on C++23, GCC 15.3 (libstdc++) · examples/cpp/collections/vector_examples.cpp

Parameters

pos
An iterator into this vector (end() appends).

Behaviour

Returns
An iterator to the inserted element.
Errors and preconditions
std::bad_alloc; exceptions from T's constructors or assignments.
Changes
size() increases by 1.
Memory and invalidation
Reallocation invalidates everything; otherwise iterators and references at or after pos are invalidated.

See it step by step: the Dynamic arrays: capacity, resizing and amortized append lesson has an interactive 3D visualizer of the same mechanism.