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.
Answers to questions are automatically generated and may not have been reviewed.
std::span
A detailed guide to creating a "view" of an array using std::span
, and why we would want to