Skip to content
DryPerspective edited this page Oct 2, 2023 · 3 revisions

A span represents a non-owning, cheap-to-copy view of a contiguous block of data. It allows the user to safely pass around and iterate through these objects without risk of going out of bounds of their desired view, or paying a performance cost to duplicate data. A span object can have static extent (in which case the size of the viewed range is known at compile time) or a dynamic extent. This is determined by the second template parameter, which defaults to dynamic extent.

dp::span matches the interface of the modern std::span, except that it supports dp::array construction rather than std::array. While it may be possible to construct a span from a range stored non-contiguously, the behaviour of such a span will be undefined.

Features

begin
cbegin
Returns an iterator to the beginning
end
cend
Returns an iterator to the end
rbegin
crbegin
Returns a reverse iterator to the beginning
rend
crend
Returns a reverse iterator to the end
front Accesses the first element
back Accesses the last element
operator[] Provides indexed access
data Returns a pointer to the viewed storage
size Returns the number of elements in the view
size_bytes Returns the total size of the viewed elements, in bytes
empty Checks if the view is empty.
first Obtains a subspan consisting of the first N elements of the sequence
last Obtains a subspan consisting of the last N elements of the sequence
subspan Obtains a subspan
as_bytes
as_writeable_bytes
Converts a span to a view of its underlying bytes

Sample code

#include <vector>

#include "cpp98/span.h"

void printSpan(dp::span<int> sp){
    typedef dp::span<int>::const_iterator Iter;
    for(Iter it = sp.begin(); it != sp.end(); ++it){
        Print(*it + ' ');
    }
    Print('\n');
}

int main(){
    int c_arr[10] = {1,2,3,4,5,6,7,8,9,10};
    printSpan(c_arr);  //Prints 1,2,3,4,5,6,7,8,9,10

    std::vector<double> vec;
    for(int i = 0; i < 5; ++i) vec.push_back(i + i/10.0);
    printSpan(vec);  //Prints 1.1, 2.2, 3.3, 4.4, 5.5
    
    dp::span<double> span = vec.subspan(2,3); //Note, no copies made
    printSpan(span); //Prints 2.2, 3.3, 4.4
}

Clone this wiki locally