ProblemsTemplatesFixed-capacity vector
IntermediateTemplates

Fixed-capacity vector

Context

Gamedev, the main loop, 16 milliseconds per frame. The profiler catches a std::vector deciding to reallocate exactly mid-boss-fight. The lead's verdict: 'heap in the hot path is a ban'. You need a vector on the stack: fixed capacity, familiar API, zero allocations.

Task

Implement StaticVector<T, N> — a sequence container that stores up to N elements in-place, with no heap allocation. It is the building block behind small-buffer optimisations and embedded code where new is forbidden.

Constraints

  • Must be a class template on <typename T, std::size_t N>
  • Must store elements in-place — no heap allocation (new, malloc, std::vector)
  • push_back past capacity throws std::length_error
  • capacity() returns N; size() tracks the live count
  • Must work for any default-constructible T (test uses int and std::string)

Before you code

  • Why does a non-type template parameter (std::size_t N) let the capacity be fixed at compile time?
  • What are the trade-offs of in-place storage versus heap allocation?
  • How would real code avoid default-constructing all N slots up front?

Tests

  • #1push_back, size and indexing
  • #2pop_back shrinks the size
  • #3Overflowing capacity throws length_error
  • #4Works with a non-trivial element type

Hints

Hint 1

A non-type template parameter like std::size_t N can size a plain member array: T data_[N];.

Hint 2

Keep a separate std::size_t size_ counter; push_back writes data_[size_++], pop_back does --size_.

Editorstatic-vector.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.