C++ · Dynamic array · container

std::vector<T>

The standard contiguous dynamic array: elements stored inline, O(1) indexing, amortized constant-time push_back.

#include <vector>
template<class T, class Allocator = std::allocator<T>> class vector;

C++23 (std::erase since C++20); tested with GCC 15.3 / libstdc++

Operations

OperationTimeWorst caseChanges the collection
push_back / emplace_backO(1) (required by the standard)O(n) on reallocationYes
insert / emplaceO(n)O(n)Yes
operator[] / atO(1)O(1)Yes
erase / pop_back / std::eraseO(n)O(n)Yes
reserve / shrink_to_fitO(n) if it reallocates, otherwise O(1)O(n) if it reallocates, otherwise O(1)Yes

"Time" shows the amortized, expected or average bound when one applies; open an operation for the full profile and its assumptions.

How it works

Representation
Three pointers (begin, end, end of capacity) into one heap allocation holding the elements themselves, not references. The standard requires amortized constant push_back; libstdc++ doubles (observed 1, 2, 4, 8, … with GCC 15), MSVC grows by 1.5×.
Ordering
Insertion order.
Duplicates
Allowed.
Mutability
Mutable. Owns its elements (RAII): destroying the vector destroys them.
Memory and ownership
Contiguous, so data() can be passed to C APIs. Capacity never shrinks automatically; shrink_to_fit is a non-binding request.
Equality and comparison
operator== compares sizes and then elements with ==. Algorithms like std::find use == on elements.

Pitfalls

  • Any reallocation (push_back past capacity, insert, reserve) invalidates all iterators, pointers and references to elements.
  • operator[] does no bounds checking: an out-of-range index is undefined behaviour. at() throws std::out_of_range.
  • std::vector<bool> is a packed bitset specialisation; its elements are not addressable bools.
  • Erasing inside a range-for loop invalidates the loop; use std::erase / std::erase_if (C++20) or the erase-remove idiom.

Alternatives

  • std::array for a fixed size
  • std::deque for both ends with stable references
  • std::span to pass a view without copying

In other languages

References