Syntax
std::span<int> values; // #include <span>Examples
C++ std::span views
Save as main.cpp and compile with a C++20 compiler, for example g++ -std=c++20 main.cpp -o example. The article states the minimum language version.
#include <span>
#include <iostream>
void doubleAll(std::span<int> values) {
for (int& value : values) value *= 2;
}
int main() {
int scores[] = {2, 3, 4};
doubleAll(scores);
std::cout << scores[0] << ' ' << scores[2] << '\n';
}- Output: 4 8. The function receives a view of all three integers and edits the array in place.
Best practices
- Keep the owner alive and avoid vector reallocation while a span exists. Use span<const T> for read-only access; unchecked indexing still requires a valid index.
Runtime & versions
Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ISO C++ resources