Examples of std::span
Example 1:
The below code demonstrates the usage std::span to create a non-owning view of an array and then prints the elements of the array.
C++
// C++ program to illustrate the use of std::span #include <iostream> #include <span> using namespace std; int main() { int arr[] = { 1, 2, 3, 4, 5 }; // Create a span of int of array span< int > span_arr(arr); for ( const auto & num : span_arr) { cout << num << " " ; } return 0; } |
Output
1 2 3 4 5
Example 2:
The below code demonstrates the usage of std::span to create a non-owning view of a std::vector<int>, and then create a sub-span from the original span.
C++
// C++ program to illustrate the initialization of span // using vector #include <iostream> #include <span> #include <vector> int main() { vector< int > vec = { 1, 2, 3, 4, 5 }; span< int > span_vec(vec); // Create a subspan form index 1 to 3 std::span< int > subspan = span_vec.subspan(1, 3); for ( const auto & num : subspan) { std::cout << num << " " ; } return 0; } |
Output
2 3 4
C++ 20 – std::span
C++20 introduced the std::span class template as part of the C++ Template Library which represents an object that provides a way to view a contiguous sequence of objects. This feature offers a flexible and efficient way to work with contiguous sequences of objects. It is defined inside <span> header file.
In this article, we will explore the concept of std::span, discuss its usage, and provide examples to showcase its capabilities.