C++ gives you two main ways to store a sequence of values with the same type: std::array (fixed-size) and std::vector (dynamic-size). Choosing between them affects both performance and code clarity.

std::array — fixed size, stack allocated

std::array is a thin wrapper around a C-style array. Its size is fixed at compile time and it lives on the stack.

#include <array>
std::array<int, 5> scores = {10, 20, 30, 40, 50};
cout << scores[2];      // 30
cout << scores.size();  // 5

Use std::array when:

  • You know the size at compile time
  • The size will never change
  • You want stack allocation for performance
  • You're replacing a C-style array with something safer

std::vector — dynamic size, heap allocated

std::vector can grow and shrink at runtime. Its memory is heap-allocated, which means slightly more overhead but no size constraints.

#include <vector>
std::vector<int> scores;
scores.push_back(10);
scores.push_back(20);
scores.push_back(30);
cout << scores.size();  // 3
scores.pop_back();
cout << scores.size();  // 2

Use std::vector when:

  • You don't know the size at compile time
  • The collection will grow or shrink at runtime
  • You're reading data from user input or a file

Performance comparison

std::array is slightly faster for small, fixed-size collections because it's stack-allocated and the compiler can optimise it more aggressively. For large collections or dynamic sizes, std::vector is the right choice — its performance is excellent in practice.

The rule of thumb

Default to std::vector. Switch to std::array only when the size is fixed and compile-time-known and you have a specific reason to prefer stack allocation (such as performance-critical tight loops or small embedded systems).

In most programs, the difference is negligible. std::vector's flexibility wins for everyday use.