- refers to a contiguous sequence of objects: C array, std::array, std::vector, std::string
- allows handling of these types in the same way
- always knows the size of the sequence (mySpan.size())
- is a kind of “view”, never owns the objects, does not allow changing of the sequence but allows changing of objects (constant range of modifiable objects)
- a span can also handle strings, the main difference when compared with std::string_view is that std::span can modify its referenced objects
Defining a span and modifying objects
#include <span>
std::vector myVec{1,2,3,4,5};
std::span<int> myDynamicSpan(myVec);
std::span<int,5> myStaticSpan(myVec); // size is known at compile time and part of the type
// Define a subspan with n-2 elements starting at second element
std::span mySubSpan (myStaticSpan.subSpan(1,myStaticSpan.size() -2); // refers to 2,3,4
// change objects: double elements referred by mySubSpan
std::transform(mySubSpan.begin(), mySubspan.end(), mySubSpan.begin(),
[](int i){return i+i;});
// myVec = {1,4,6,8,5}
Useful member functions
- sp[i]
directly access i-th element - sp.size()
number of elements within the sequence - sp.empty()
checkls if sequence is empty - sp.first(N)
subspan containing the first N elements - sp.last(N)
subspan containing the last N elements - sp.subspan(first, N)
subspan containing N elements starting at first