std::vector<T> · C++

push_back / emplace_back

Appends an element at the end (emplace_back constructs it in place).

void push_back(const T& value); void push_back(T&& value); template<class... Args> T& emplace_back(Args&&... args);

Complexity

Best caseO(1)
AmortizedO(1) (required by the standard)
Worst caseO(n) on reallocation
Extra spaceO(1) amortized

With spare capacity, construct one element at end(). Otherwise allocate a larger buffer, move or copy all elements, destroy the old ones; geometric growth amortizes this.

Tested example

std::vector<int> v;
v.reserve(2);
v.push_back(10);
v.push_back(20);
v.push_back(30);  // size == capacity: reallocates and moves the elements
assert(v.size() == 3 && v.capacity() >= 3);
v.emplace_back(40);  // constructs the element in place
Runs in the test suite on C++23, GCC 15.3 (libstdc++) · examples/cpp/collections/vector_examples.cpp

Parameters

value / args
The element, or constructor arguments for it.

Behaviour

Returns
push_back: nothing. emplace_back: a reference to the new element (C++17).
Errors and preconditions
Allocation failure throws std::bad_alloc. If T's move constructor can throw and T is copyable, the vector copies on reallocation to keep the strong exception guarantee.
Changes
size() increases by 1; may reallocate.
Memory and invalidation
If the size exceeds the capacity, all iterators, pointers and references are invalidated; otherwise only end() is.

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