Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Containers

C++ std::vector class

Reference for std::vector: construction, element access, iterators, capacity, modifiers, complexity, invalidation rules and the differences from arrays.

std::vector<T> is a sequence container that stores its elements contiguously in a dynamically allocated array and grows automatically as you add elements. It supports O(1) indexed access, amortized O(1) appends at the end, and linear-time insertion and erasure elsewhere. Because the storage is contiguous, v.data() can be passed to C APIs and iteration is very cache-friendly.

A vector owns its elements: copying it copies them, destroying it destroys them, and moving it transfers the buffer. It lives in <vector>; T must be destructible, and more operations require more of T (copy- or move-insertable, and so on).

C++
#include <vector>
std::vector<int> v = {1, 2, 3};
v.push_back(4);

Try it

C++ Constructing, accessing and modifying

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ Copy, move, compare and 2D vectors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
template <class T, class Allocator = std::allocator<T>>
class vector;

// Construction
vector();                                   vector(size_type n);
vector(size_type n, const T& value);        vector(InputIt first, InputIt last);
vector(std::initializer_list<T>);           vector(const vector&);   vector(vector&&) noexcept;

// Access
T& operator[](size_type i);   T& at(size_type i);
T& front();   T& back();      T* data() noexcept;

// Capacity
size_type size() const;   bool empty() const;   size_type capacity() const;
void reserve(size_type n);   void shrink_to_fit();

// Modifiers
void push_back(const T&);   void pop_back();   iterator insert(...);   iterator erase(...);
void resize(size_type n);   void clear() noexcept;   void swap(vector&) noexcept;
Name Description
n Number of elements. Size arguments of vector(n) default-construct (value-initialize) n elements.
i Zero-based index. operator[] does not check it; at() throws.
first, last Input iterator range copied into the vector.
value Value copied into each new element.

Returns: access functions return references; size() returns an unsigned count; data() returns a pointer to the first element (may be null if the vector is empty).

Errors / undefined behavior:

  • at(i) throws std::out_of_range when i >= size().
  • v[i] with i >= size(), front()/back() on an empty vector, and pop_back() on an empty vector are undefined behavior.
  • Operations that must grow the buffer can throw std::bad_alloc or std::length_error (more than max_size()).

Usage notes

  • {} versus (): std::vector<int> v(3, 7) makes three sevens, but std::vector<int> v{3, 7} makes two elements, 3 and 7. Brace initialization prefers the initializer-list constructor.
  • Complexity: indexing and push_back (amortized) are O(1); insertion or erase at the front or middle is O(n); clear is O(n) for non-trivial types but keeps the capacity.
  • Iterators and references are invalidated whenever the buffer is reallocated and by inserting or erasing before them. See iterator invalidation.
  • Pass by const reference (const std::vector<int>&) or use std::span<const int> for parameters; return by value (it is moved or elided).
  • Don't compare indexes with int carelessly: size() is unsigned, so i < v.size() - 1 underflows on an empty vector.
  • vector<bool> is different: it packs bits and has no real bool&; see vector<bool>.
  • Removing by value needs the erase-remove idiom or std::erase (C++20); see erase-remove.
  • Hot loops: reserve capacity ahead with reserve when you know the final size.
  • Since C++20 vector members are constexpr, so vectors can be used in constant evaluation if they are destroyed before it ends.
  • std::vector<std::vector<T>> is not contiguous overall; for a matrix, one flat vector with index arithmetic is faster.