According to the latest C++20 draft, a span is a non-owning view over a contiguous sequence of objects. In other words, a std::span is, in essence, a pointer, length pair that gives the user a view into a contiguous sequence of elements. The elements of a span can be, for example, stored in one of the standard library sequential containers (like std::array, std::vector), in a built-in C-style array or in a memory buffer.
Here is a simple example of using std::span as a general interface for a print function that receives as argument a contiguous sequence of integers:
This is what I see if I build and run the above file on a Linux machine with Clang 9:
At the time of this writing, you can use std::span with Clang 9 and GCC 10, MSVC doesn’t have support for std::span. If you are using a compiler that doesn’t have support for std::span, you can use a 3rd party implementation like @tcbrindle or use the latest Clang or GCC from Compiler Explorer.
Here is an example of modifying the above program for a C++17 compiler. I assume that you’ve saved the span.hpp header from @tcbrindle in the same folder as your span_0.cpp file:
With the above modification, this is how you can build the example with the latest MSVC compiler:
Please note that while std::span doesn’t own the memory storage of the elements, as in you can’t increase or decrease the memory buffer that stores the elements, you can modify the actual elements, e.g.:
This is what I see, if I build and run the above program:
You can also create a span from a pointer to a memory buffer and a size, e.g. :
This is what I see, if I build and run the above program:
You can also create subviews, or subspans, from a span and operate on these. Keep in mind that when you modify a span or a subspan element you are actually modifying the original data, e.g.:
This is what you should see, if you build and run the above code:
Say that you want to sort a subspan from an existing contiguous sequence of integers. Here is an example of creating a subspan from an existing C-array, taking a subspan from the above span, without the first and the last elements and sorting the selected subspan:
This is what you should see, if you build and run the above code:
As a side note, don’t confuse C++17 std::string_view with the std::span introduced by C++20. While both are non-owning views, std::string_view is a read-only view.
You can, obviously, create a modifiable span or subspan from a std::string or from a char pointer and a buffer size pair. Here is a simple example, that works only for ASCII strings:
This is what you should see, if you build and run the above code:
You can find the complete source code on the GitHub repository for this article.
If you want to learn more about C++17 I would recommend reading C++17 in Detail by Bartlomiej Filipek: