ProblemsTemplatesNon-owning span
IntermediateTemplates

Non-owning span

Context

Half the functions in the project take const std::vector<int>&, the other half take (const int*, size_t), with an eternal customs checkpoint of copies between them. The new tech lead looked at it, sighed, and filed 'we need a span' into tech debt. The tech debt got assigned to you. Write the non-owning view: pointer + length, zero allocations.

Task

Implement Span<T> — a lightweight, non-owning view over a contiguous range (a pointer + a length). It is the idiom behind std::span: pass arrays and vectors to functions without copying and without coupling to a specific container.

Constraints

  • Must be a class template on <typename T>
  • Must be non-owning: store only a pointer and a length — allocate nothing, copy no elements (new/malloc forbidden)
  • Constructible from (T* data, size_t size) and from a C array T(&)[N]
  • Mutating through the span writes through to the underlying storage
  • Provide begin()/end() so it works in a range-based for

Before you code

  • Why is a span cheap to copy while the data it views is not?
  • What lifetime hazard does a non-owning view introduce?
  • How does a templated array constructor capture the length N automatically?

Tests

  • #1View over a C array: size and indexing
  • #2Mutation writes through to the underlying storage
  • #3Constructs from a pointer + length (e.g. vector data)
  • #4Range-based for via begin/end

Hints

Hint 1

Store exactly two members: T* data_ and std::size_t size_. Everything else is computed from them.

Hint 2

The array constructor template <std::size_t N> Span(T (&arr)[N]) deduces N, so you can call Span(data_, N) semantics: data_ = arr; size_ = N;.

Editorspan-view.cpp
Results

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