Open In App

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.



Syntax

std::span <type> span_name;

where type is the type of object in the sequence.

Initialization of std::span

We can initialize std::span using 3 methods:



1. From an array:

std::span<int> span_name(array_name);

2. From a vector:

std::span<int> span_name(vector_name);

3. From a string:

std::span<char> span_name(string_name);

Member functions of std::span

A span has the following member functions used to perform various operations:

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

Features of std::span

Conclusion

Spans are a powerful new feature in C++ 20 that can make your code safer, more convenient, and more efficient. If you’re not already using spans, I encourage you to give them a try.


Article Tags :
C++