C++ vector vs array: which should you use?

The short answer first, then the details that actually matter in interviews and real code.

The 10-second answer

Default to std::vector. Use a C-style array only when a fixed size is part of the problem (and use std::array rather than the raw kind). Everything below explains why, because "just use vector" won't survive a follow-up question.

Three containers, one idea

C-style arraystd::arraystd::vector
SizeFixed at compile timeFixed at compile timeGrows and shrinks at runtime
Lives where?Where you declare it (stack if local)Where you declare itData on the heap; object itself can live anywhere
Knows its length?No — you track it separatelyYes — .size()Yes — .size()
Copyable?No (decays to a pointer)YesYes
Pass to a functionAwkward (becomes a pointer, size is lost)CleanClean
Bounds checkingNone.at() checks.at() checks, [] doesn't

What each looks like

#include <array>
#include <vector>

int main() {
    int raw[5] = {1, 2, 3, 4, 5};          // C-style: size is part of the type
    std::array<int, 5> fixed = {1, 2, 3, 4, 5}; // fixed size, but a real type
    std::vector<int> grow = {1, 2, 3};     // resizable

    grow.push_back(4);                     // now holds 1 2 3 4
    return 0;
}

Note: our in-browser playground currently covers the beginner core (iostream, cmath, cstdio…), so run snippets like these on your desktop compiler — or in the playground once full-container support lands.

Why vector wins by default

When an array (the fixed kind) is genuinely better

Interview follow-ups worth knowing

  1. "How does vector grow?" When it hits capacity, it allocates a bigger block (commonly ~1.5× or 2×) and moves elements over — that's why repeated push_back is still amortized O(1).
  2. "What's vector<bool>?" A trick question: it's a bit-packed specialization that doesn't behave like a normal vector of values.
  3. "Difference between size() and capacity()?" size() = elements in use; capacity() = slots allocated before the next regrow.
  4. "Can vector invalidate pointers?" Yes — any growth or insert/erase may move the storage. Don't keep raw pointers/references into a vector across modifications.

Rule of thumb

Write std::vector until you have a measured reason not to. Fixed-size-by-nature? Reach for std::array. Raw C arrays are for interfacing with C code and memory-constrained embedded work — and even then, wrapped.