Span vs Vector in C++

When should I use std::span over std::vector in C++? What are the key differences and trade-offs between these two types?

The main differences between std::span and std::vector are:

Ownership

std::vector owns the elements it contains. It manages the memory allocation and deallocation for those elements.

std::span does not own the elements it references. It simply provides a view into a contiguous sequence of elements stored elsewhere.

Size

The size of a std::vector can change dynamically at runtime. Elements can be added or removed from a vector.

The size of a std::span is fixed at the time it is created. A span cannot change the number of elements it references.

Memory Allocation

std::vector allocates its own memory to store elements. This allocation happens on the heap.

std::span does not allocate any memory. It simply holds a pointer to elements stored elsewhere, either on the stack or the heap.

Cost of Copying

Copying a std::vector is an expensive operation because it involves allocating new memory and copying all the elements.

Copying a std::span is cheap, it only involves copying a pointer and a size.

You should use std::span when you want a lightweight, non-owning view into a sequence of elements, and you don't need to change the size of that sequence. This is often useful for passing arrays to functions:

#include <span>
#include <vector>

void Process(std::span<const int> data) {
  for (int i : data) {
    // Process each element
  }
}

int main() {
  std::vector<int> v{1, 2, 3, 4, 5};
  Process(v);
}

Use std::vector when you need ownership of the elements, or when you need to be able to change the number of elements dynamically.

Array Spans and std::span

A detailed guide to creating a "view" of an array using std::span, and why we would want to

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Creating a Span from a Vector
How can I create a std::span from a std::vector in C++? Can you provide an example?
Span Size and Stack Overflow
Is there a limit to the size of a std::span? Could creating a very large std::span lead to a stack overflow?
Lifetime of a Span
What happens if I create a std::span from a vector, and then the vector goes out of scope? Is it safe to continue using the span?
Modifying Elements Through a Span
If I modify an element through a std::span, does it affect the original data? Can you show an example?
Using Span as a Function Parameter
What are the benefits of using std::span as a function parameter instead of a reference to a container like std::vector or std::array?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant