Creating a Span from a Vector

How can I create a std::span from a std::vector in C++? Can you provide an example?

You can create a std::span from a std::vector by passing the vector to the std::span constructor. Here's an example:

#include <iostream>
#include <span>
#include <vector>

void PrintSpan(std::span<const int> data) {
  for (int i : data) {
    std::cout << i << " ";
  }
  std::cout << "\n";
}

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

  PrintSpan(span);
}
1 2 3 4 5

In this example, we create a std::vector<int> called vec with some initial values. We then create a std::span<int> called span by passing vec to its constructor.

We can pass span to functions that expect a std::span, like PrintSpan in this example. PrintSpan takes a std::span<const int>, which allows it to read the elements but not modify them.

Note that the std::span does not own the data. If the original std::vector goes out of scope or is modified, the std::span will be affected.

Also, if you have a const std::vector, you should create a std::span<const T> to avoid any accidental modifications:

const std::vector<int> vec{1, 2, 3, 4, 5};
std::span<const int> span{vec};

This way, the constness of the original vector is carried over to the span.

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.

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?
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