Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 171 ยท Arrays and Vectors

std::vector

Learn std::vector, the dynamic array of C++ - creating vectors, push_back and emplace_back, size vs capacity, reserve, insert and erase, iteration and common pitfalls.

std::vector<T> is a dynamic array: a sequence of elements stored contiguously in memory, just like std::array, except that it can grow and shrink while the program runs. You don't need to know in advance how many lines a file has, how many orders a customer placed, or how many enemies are on screen. You just add elements, and the vector finds room for them.

It is the most used container in C++, and the right default whenever you need "a list of things". The language's own designers recommend reaching for std::vector first and switching to something else only when you have a measured reason. This lesson covers everything you need for daily use: creating vectors, adding and removing elements, the difference between size and capacity, iterating, and the pitfalls that catch newcomers. std::vector in Depth goes further into growth strategy and performance.

Creating a vector

Include <vector> and give the element type in angle brackets:

C++
#include <vector>

std::vector<int> empty;                    // no elements
std::vector<int> primes{2, 3, 5, 7};       // four elements from a list
std::vector<double> zeros(5);              // five elements, all 0.0
std::vector<char> stars(3, '*');           // three elements, all '*'
std::vector names{"Ada", "Grace"};         // CTAD: std::vector<const char*>
std::vector<int> copy = primes;            // a full, independent copy

Unlike a local array, a vector is never "uninitialized": std::vector<int> v(5) gives five zeros, and an empty vector is a valid, ready-to-use object.

Braces vs parentheses: a famous trap

Braces mean "these are the elements". Parentheses mean "call a constructor with these arguments". For most types this is a detail, but for vectors of numbers it changes the meaning completely:

C++ Braces vs parentheses

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.

When a type has a constructor taking an std::initializer_list (as vector does), a braced list prefers it. So is "one element, five" and (5) is "five elements". The std::vector<std::string> case shows the other side of the rule: 3 can't be a string, so the braces fall back to the "count and value" constructor and you get three "hi"s. Remember the rule as: use () for a size, {} for a list of values.

Adding elements

push_back appends a copy of a value to the end. emplace_back builds the new element directly in the vector from constructor arguments. Both run in amortized constant time, which in plain words means "very fast on average".

C++ Building a vector from input

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.

The vector starts empty and grows to fit however many lines are in the Input box. Add a fifth line and run again. emplace_back(name, population) passes its arguments to the std::pair constructor; with push_back you would write cities.push_back({name, population}). For simple types like int there is no difference. For complex objects, emplace_back can skip a temporary, though in practice modern compilers make the gap small. Pick whichever reads better.

To add in the middle, use insert with an iterator, an object that marks a position (v.begin() is the first element, v.end() is one past the last):

C++
std::vector<int> v{10, 20, 40};
v.insert(v.begin() + 2, 30);          // {10, 20, 30, 40}
v.insert(v.begin(), 2, 0);            // two zeros at the front: {0, 0, 10, 20, 30, 40}
v.insert(v.end(), {50, 60});          // append a list: {..., 40, 50, 60}

Inserting anywhere but the end has to shift every later element one place to the right, so it costs time proportional to the number of elements after the position. A few inserts are fine; thousands of front inserts into a large vector are slow, and that's when other containers or a different algorithm are worth considering.

Accessing elements

The access functions match std::array:

Expression Meaning If out of range or empty
v[i] Element i, unchecked Undefined behavior
v.at(i) Element i, checked Throws std::out_of_range
v.front(), v.back() First and last elements Undefined behavior on an empty vector
v.data() Pointer to the first element May be null for an empty vector
v.size(), v.empty() Number of elements, and whether it is 0 n/a

Two habits prevent most crashes: check empty() before calling front(), back() or pop_back(), and use at() for indexes you haven't validated yourself. Prefer v.empty() over v.size() == 0; it says what you mean.

Size vs capacity

A vector keeps track of two numbers:

  • size(): how many elements it currently holds.
  • capacity(): how many elements fit in the memory it has already allocated.

When you push_back and size() == capacity(), the vector must reallocate: get a bigger block of memory, move all existing elements into it, and free the old block. To keep this rare, it grows geometrically. GCC's library doubles the capacity each time, so a million push_back calls trigger only about twenty reallocations. That's why appending is "amortized constant time".

C++ Watching capacity grow

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.

The first vector reallocates at sizes 1, 2, 3, 5, 9, 17, 33 and 65, reaching capacity 128. The second one, after reserve(70), never reallocates. The growth factor is not specified by the standard: Microsoft's library grows by 1.5ร— instead, so don't write code that depends on exact capacities.

When you know roughly how many elements are coming, call reserve first. It doesn't change the size, only the capacity. Don't confuse it with resize:

  • reserve(n) allocates room for n elements; size() is unchanged, so you still push_back.
  • resize(n) changes the number of elements: it adds value-initialized elements (zeros) or removes them from the end.

A classic bug is calling reserve(10) and then writing v[0] = 1: the vector still has size 0, so that's undefined behavior. Notice also that clear() removes the elements but keeps the capacity, ready for reuse. To actually release memory, call shrink_to_fit() after clearing (it's a request the library may ignore, though GCC honors it).

Removing elements

C++
std::vector<int> v{1, 2, 3, 4, 5, 6};
v.pop_back();                          // remove the last element: {1, 2, 3, 4, 5}
v.erase(v.begin());                    // remove the first: {2, 3, 4, 5}
v.erase(v.begin() + 1, v.begin() + 3); // remove a range [1, 3): {2, 5}
v.clear();                             // remove everything: {}

Removing by value or by condition is so common that C++20 added two free functions, std::erase and std::erase_if, which return how many elements they removed:

C++ Removing elements

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.

The [](int r) { return r > 100; } part is a lambda, a small unnamed function passed as an argument; Lambda Expressions covers them fully. Before C++20 the same job needed the "erase-remove idiom", v.erase(std::remove(v.begin(), v.end(), -1), v.end()), which you'll still see in older code.

pop_back serves from the end, so the names come out in reverse order. A vector is efficient at the back and slow at the front; if you need a real first-in-first-out queue, see Container Adapters.

Iterating over a vector

All the loop styles you know work:

C++
std::vector<std::string> tags{"cpp", "stl", "vector"};

for (const auto& tag : tags) { }     // read: no copies
for (auto& tag : tags) { }           // modify each element
for (std::size_t i = 0; i < tags.size(); ++i) { }   // need the index

Use const auto& when you only read, especially for strings and other large elements. Plain auto copies every element, which works but wastes time. If you need a signed index (for example to count down), std::ssize(tags) returns the size as a signed number, avoiding the unsigned traps from Integer Types.

Vectors are values

Like std::array and std::string, a vector behaves like a value: = copies all elements, == compares sizes and contents, < compares lexicographically, and you can pass and return vectors freely. Returning a vector from a function is cheap, because the compiler either builds it directly in the caller's variable or moves it (hands over its internal pointer) instead of copying. Passing one into a function by value does copy it, so read-only parameters should be const std::vector<T>& (see Parameters).

C++ Vectors as values and grids

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.

The last part builds Pascal's triangle in a std::vector<std::vector<int>>, where each inner vector is a row of a different length. Grids and matrices have their own lesson next, Multidimensional Arrays and Matrices, including a faster flat layout.

Iterator invalidation: a preview

Because a vector moves its elements when it reallocates, anything that points into it (references, pointers and iterators to elements) can be left pointing at freed memory. This is called invalidation:

C++
std::vector<int> v{1, 2, 3};
int& first = v[0];
v.push_back(4);           // may reallocate and move every element
std::println("{}", first); // UB if it did: first refers to the old memory

The same applies to adding elements while looping over a vector with range-based for: the loop's hidden iterators break the moment the vector reallocates. The rules in short:

  • push_back, emplace_back, insert and resize invalidate everything if they reallocate; otherwise they invalidate only positions at or after the change.
  • erase and pop_back invalidate the erased elements and everything after them.
  • reserve up front, or holding indexes instead of references, avoids the problem.

Iterators covers the full rules. For now: don't keep references into a vector across operations that change its size.

Common mistakes

  • std::vector<int> v{10} when you meant ten elements. Use parentheses for a count.
  • Indexing an empty or reserved vector. reserve doesn't create elements; v[0] after reserve is UB. Use push_back or resize.
  • v.size() - 1 on an empty vector. size() is unsigned, so it wraps to a huge number. Check empty() first.
  • Copying by accident. for (auto s : strings) and void f(std::vector<T> v) copy. Use const auto& and const std::vector<T>& for read-only access.
  • std::vector<bool> is a special space-saving version that stores bits, not bools, and behaves oddly (you can't take a bool& to an element). It's explained in std::vector in Depth.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is v.size() after std::vector<int> v{8};?

    Braces list the elements, so v holds a single element with the value 8. std::vector<int> v(8) would create eight zeros.
  2. 2. std::vector<int> v; v.reserve(100); What is true now?

    reserve only allocates memory. The vector still has no elements, so v[0] would be undefined behavior; use push_back or resize to add elements.
  3. 3. What does this print? std::vector<int> v{1, 2, 3, 2, 1}; std::erase(v, 2); std::println("{}", v);

    std::erase (C++20) removes every element equal to the value, not just the first one.
  4. 4. What happens to capacity() when you call clear() on a vector?

    clear() sets the size to 0 but keeps the allocated memory for reuse. Call shrink_to_fit() afterwards to ask for the memory to be released.
  5. 5. Why is holding int& x = v[0]; and then calling v.push_back(42); dangerous?

    If size() equals capacity(), push_back moves every element to a new block of memory, so old references, pointers and iterators become invalid.

Summary

  • std::vector<T> (from <vector>) is a contiguous, growable array and the default container in C++.
  • Use () for a count (v(5), v(3, 7)) and {} for a list of elements (v{5} has one element).
  • push_back copies a value to the end; emplace_back constructs in place; insert adds anywhere but shifts later elements.
  • size() is the element count, capacity() the allocated room. Growth is geometric; reserve avoids repeated reallocation; resize changes the size.
  • Remove with pop_back, erase, clear, and C++20's std::erase / std::erase_if.
  • Vectors copy with =, compare with ==, and return cheaply from functions. Pass them by const& to read.
  • Reallocation invalidates references, pointers and iterators into the vector.

Next: Multidimensional Arrays and Matrices, where you'll store grids as nested arrays, vectors of vectors, and fast flat vectors.