Lesson 87 +10 XP

std::vector Resizing and Capacity

std::vector Resizing and Capacity

A vector tracks two related but different numbers: its size and its capacity.

Size vs capacity

  • Size - the number of elements actually in the vector right now.
  • Capacity - how many elements the vector's memory can hold without allocating a fresh, bigger block.
std::vector<int> v;
v.reserve(10);            // sets capacity
std::cout << v.capacity();   // 10 (memory waiting)
std::cout << v.size();       // 0 (still no elements)

Capacity is always at least as large as size.

resize vs reserve

  • v.resize(n) changes the actual size to n, adding default elements or trimming extras: v.resize(5) makes the vector hold 5 elements.
  • v.reserve(n) only makes room (grows capacity) - the element count doesn't change.

Stack-like behavior at the back

The back of a vector is cheap to modify:

v.push_back(9);      // append to the back
int last = v.back(); // look at the back element
v.pop_back();        // remove the last element

Last in, first out - exactly like a stack. That's why vectors make good stacks.

Bounds-checked with at()

v[i] is fast but unchecked. v.at(i) always checks the index and throws an exception if you go too large - same between out-of-range and undefined behavior:

v.at(2)   // throws if there is no index 2

Prefer at() when you want safety, [] when you know the index is valid and want max speed.

TL;DR

  • Size = elements now; capacity = storage available.
  • capacity >= size is always true.
  • resize(n) changes the element count; reserve(n) only allocates.
  • push_back, back, and pop_back work at the back like a stack.
  • at(i) checks bounds and throws on out-of-range; [i] doesn't.