Search⌘ K
AI Features

Arrays vs. Vectors

Explore the characteristics of static arrays and std::vector, including their use cases in C++. Learn to choose the right container based on size requirements, performance needs, and flexibility for efficient data handling in C++ algorithms.

Now that we have covered both static arrays and std::vector, it is important to understand how they compare and when to use each one. Choosing the right container for the task is a fundamental skill in C++ DSA.

Quick comparison

Property

Arrays

Vectors

Size

Fixed at compile time

Grows and shrinks at runtime

Memory allocation

Stack (typically)

Heap

Access speed

O(1), direct

O(1), direct

Resizing

Not possible

Amortized O(1) per insertion

Cache locality

Excellent

Excellent

Memory overhead

None

Small (typically 3 pointers: begin, end, capacity)

Bounds checking

No (with [])

Optional (.at() throws on out of bounds)

Passing to functions

Decays to pointer, loses size info

Passed as object, size is preserved

Member functi

None

Rich set (.push_back, .pop_back, .size, etc.)

Header required

None

<vector>

When to use a static array

Static arrays are the right choice when:

  • The size is known at compile time and will never change. For example, storing the number of days in each month, a fixed-size lookup table, or ...