Systems CourseC/C++ · Linux · Memory
C++ Language & SafetyLesson 21 of 441 min read6 questions

std::array vs std::vector

Fixed size vs growable; pick by whether the count is known.

Test yourself ↓

Concept core idea Watch out easy to get wrong

Concept

Key concepts

  1. std::array<T,N> = fixed size baked in at compile time; cannot grow. Lives on the stack (no heap).
  2. std::vector<T> = dynamic; grows at runtime with push_back/resize. Backed by the heap.
  3. Both offer [] (unchecked) and .at() (checked), and .size() to loop safely.
  4. Fixed, known count → array. Varies/grows → vector.

Choosing

C++
std::array<int,5> a = {10,20,30,40,50};
std::vector<int> v; v.push_back(10); v.push_back(20);
Watch out

Easily confused

array vs vector
array = fixed compile-time size, stack, no growth. vector = dynamic, heap, push_back to grow.
size vs capacity
array's size is fixed forever. vector has a size (elements) and a capacity (allocated room) that grows as needed.

Test yourself

6 questions on this lesson. Write your answers from memory, then compare them with the model answers side by side.