Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/container/span"

From cppreference.com
< cpp‎ | container
m (Helper template: qualify enable_safe_range)
m (-`inline`: CWG2387)
 
(58 intermediate revisions by 21 users not shown)
Line 2: Line 2:
 
{{cpp/container/span/navbar}}
 
{{cpp/container/span/navbar}}
 
{{dcl begin}}
 
{{dcl begin}}
{{dcl header | span}}
+
{{dcl header|span}}
{{dcl | since=c++20 |1=
+
{{dcl|since=c++20|1=
template<  
+
template<
     class T,  
+
     class T,
 
     std::size_t Extent = std::dynamic_extent
 
     std::size_t Extent = std::dynamic_extent
 
> class span;
 
> class span;
Line 11: Line 11:
 
{{dcl end}}
 
{{dcl end}}
  
The class template {{tt|span}} describes an object that can refer to a contiguous sequence of objects with the first element of the sequence at position zero. A {{tt|span}} can either have a ''static'' extent, in which case the number of elements in the sequence is known and encoded in the type, or a ''dynamic'' extent.
+
The class template {{tt|span}} describes an object that can refer to a contiguous sequence of objects with the first element of the sequence at position zero. A {{tt|span}} can either have a ''static'' extent, in which case the number of elements in the sequence is known at compile-time and encoded in the type, or a ''dynamic'' extent.
  
A typical implementation holds only two members: a pointer to {{tt|T}} and a size.
+
For a {{tt|span}} {{c|s}}, pointers, iterators, and references to elements of {{c|s}} are invalidated when an operation invalidates a pointer in the range {{range|s.data()|s.data() + s.size()}}.
 +
 
 +
{{rrev|since=c++23|
 +
Every specialization of {{tt|std::span}} is a {{named req|TriviallyCopyable}} type.
 +
}}
 +
 
 +
A typical implementation holds a pointer to {{tt|T}}, if the extent is dynamic, the implementation also holds a size.
  
 
===Template parameters===
 
===Template parameters===
 
{{par begin}}
 
{{par begin}}
{{par | T | element type; must be a complete type that is not an abstract class type}}
+
{{par|T|element type; must be a complete object type that is not an abstract class type}}
{{par | Extent | the number of elements in the sequence, or {{tt|std::dynamic_extent}} if dynamic }}
+
{{par|Extent|the number of elements in the sequence, or {{tt|std::dynamic_extent}} if dynamic}}
 
{{par end}}
 
{{par end}}
  
 
===Member types===
 
===Member types===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc hitem | Member type | Definition}}
+
{{dsc hitem|Member type|Definition}}
{{dsc | {{tt|element_type}} | {{tt|T}} }}
+
{{dsc|{{tt|element_type}}|{{tt|T}}}}
{{dsc | {{tt|value_type}} | {{c|std::remove_cv_t<T>}} }}
+
{{dsc|{{tt|value_type}}|{{c/core|std::remove_cv_t<T>}}}}
{{dsc | {{tt|size_type}} | {{lc|std::size_t}} }}
+
{{dsc|{{tt|size_type}}|{{lc|std::size_t}}}}
{{dsc | {{tt|difference_type}} | {{lc|std::ptrdiff_t}} }}
+
{{dsc|{{tt|difference_type}}|{{lc|std::ptrdiff_t}}}}
{{dsc | {{tt|pointer}} | {{tt|T*}} }}
+
{{dsc|{{tt|pointer}}|{{c/core|T*}}}}
{{dsc | {{tt|const_pointer}} | {{tt|const T*}} }}
+
{{dsc|{{tt|const_pointer}}|{{c/core|const T*}}}}
{{dsc | {{tt|reference}} | {{tt|T&}} }}
+
{{dsc|{{tt|reference}}|{{c/core|T&}}}}
{{dsc | {{tt|const_reference}} | {{tt|const T&}} }}
+
{{dsc|{{tt|const_reference}}|{{c/core|const T&}}}}
{{dsc | {{tt|iterator}} | implementation-defined {{named req|RandomAccessIterator}}, {{named req|ConstexprIterator}}, and {{named req|ContiguousIterator}} whose {{tt|value_type}} is {{tt|value_type}} }}
+
{{dsc|{{tt|iterator}}|implementation-defined {{named req|RandomAccessIterator}}, {{named req|ConstexprIterator}}, and {{lconcept|contiguous_iterator}} whose {{tt|value_type}} is {{tt|value_type}}}}
{{dsc | {{tt|const_iterator}} | implementation-defined constant {{named req|RandomAccessIterator}}, {{named req|ConstexprIterator}}, and {{named req|ContiguousIterator}} whose {{tt|value_type}} is {{tt|value_type}} }}
+
{{dsc|{{tt|const_iterator}} {{mark since c++23}}|{{c/core|std::const_iterator<iterator>}}}}
{{dsc | {{tt|reverse_iterator}} | {{c|std::reverse_iterator<iterator>}} }}
+
{{dsc|{{tt|reverse_iterator}}|{{c/core|std::reverse_iterator<iterator>}}}}
{{dsc | {{tt|const_reverse_iterator}} | {{c|std::reverse_iterator<const_iterator>}} }}
+
{{dsc|{{tt|const_reverse_iterator}} {{mark since c++23}}|{{c/core|std::const_iterator<reverse_iterator>}}}}
 
{{dsc end}}
 
{{dsc end}}
  
Note: {{tt|iterator}} is a mutable iterator if {{tt|T}} is not const-qualified.
+
{{petty|Note: {{tt|iterator}} is a mutable iterator if {{tt|T}} is not const-qualified.}}
  
All requirements on the iterator types of a {{named req|Container}} apply to the {{tt|iterator}} and {{tt|const_iterator}} types of {{tt|span}} as well.
+
All requirements on the iterator types of a {{named req|Container}} apply to the {{tt|iterator}} type of {{tt|span}} as well.
  
 
===Member constant===
 
===Member constant===
{{ddcl|1=
+
{{dsc begin}}
static constexpr std::size_t extent = Extent;
+
{{dsc hitem|Name|Value}}
}}
+
{{dsc mem sconst|nolink=true|{{dsc small|{{c/core|constexpr std::size_t}}}} extent|{{c|Extent}}}}
 +
{{dsc end}}
  
 
===Member functions===
 
===Member functions===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc inc | cpp/container/span/dsc constructor}}
+
{{dsc inc|cpp/container/span/dsc constructor}}
{{dsc inc | cpp/container/span/dsc operator{{=}}}}
+
{{dsc inc|cpp/container/span/dsc operator{{=}}}}
 +
{{dsc mem dtor|nolink=true|notes={{mark implicit}}|destructs a {{tt|span}}}}
  
{{dsc h2 | Iterators}}
+
{{dsc h2|Iterators}}
{{dsc inc | cpp/container/span/dsc begin}}
+
{{dsc inc|cpp/container/dsc begin|span}}
{{dsc inc | cpp/container/span/dsc end}}
+
{{dsc inc|cpp/container/dsc end|span}}
{{dsc inc | cpp/container/span/dsc rbegin}}
+
{{dsc inc|cpp/container/dsc rbegin|span}}
{{dsc inc | cpp/container/span/dsc rend}}
+
{{dsc inc|cpp/container/dsc rend|span}}
  
{{dsc h2 | Element access}}
+
{{dsc h2|Element access}}
{{dsc inc | cpp/container/dsc front | span}}
+
{{dsc inc|cpp/container/dsc front|span}}
{{dsc inc | cpp/container/dsc back | span}}
+
{{dsc inc|cpp/container/dsc back|span}}
{{dsc inc | cpp/container/span/dsc operator_at}}
+
{{dsc inc|cpp/container/dsc at|span}}
{{dsc inc | cpp/container/span/dsc data}}
+
{{dsc inc|cpp/container/dsc operator_at|span}}
 +
{{dsc inc|cpp/container/dsc data|span}}
  
{{dsc h2 | Observers}}
+
{{dsc h2|Observers}}
{{dsc inc | cpp/container/span/dsc size}}
+
{{dsc inc|cpp/container/dsc size|span}}
{{dsc inc | cpp/container/span/dsc size_bytes}}
+
{{dsc inc|cpp/container/span/dsc size_bytes}}
{{dsc inc | cpp/container/span/dsc empty}}
+
{{dsc inc|cpp/container/span/dsc empty}}
  
{{dsc h2 | Subviews}}
+
{{dsc h2|Subviews}}
{{dsc inc | cpp/container/span/dsc first}}
+
{{dsc inc|cpp/container/span/dsc first}}
{{dsc inc | cpp/container/span/dsc last}}
+
{{dsc inc|cpp/container/span/dsc last}}
{{dsc inc | cpp/container/span/dsc subspan}}
+
{{dsc inc|cpp/container/span/dsc subspan}}
 
{{dsc end}}
 
{{dsc end}}
  
 
===Non-member functions===
 
===Non-member functions===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc inc | cpp/container/span/dsc as_bytes}}
+
{{dsc inc|cpp/container/span/dsc as_bytes}}
{{dsc inc | cpp/container/span/dsc get}}
+
 
{{dsc end}}
 
{{dsc end}}
  
 
===Non-member constant===
 
===Non-member constant===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc inc | cpp/container/span/dsc dynamic_extent}}
+
{{dsc inc|cpp/container/span/dsc dynamic_extent}}
 
{{dsc end}}
 
{{dsc end}}
  
===Helper classes===
+
===Helper templates===
{{dsc begin}}
+
{{ddcl|since=c++20|1=
{{dsc inc | cpp/container/span/dsc tuple_size}}
+
template< class T, std::size_t Extent >
{{dsc inc | cpp/container/span/dsc tuple_element}}
+
constexpr bool ranges::enable_borrowed_range<std::span<T, Extent>> = true;
{{dsc end}}
+
}}
 +
This specialization of {{lc|ranges::enable_borrowed_range}} makes {{tt|span}} satisfy {{lconcept|borrowed_range}}.
  
===Helper template===
+
{{ddcl|since=c++20|1=
{{ddcl|1=
+
template< class T, std::size_t Extent >
template<class T, std::size_t Extent>
+
constexpr bool ranges::enable_view<std::span<T, Extent>> = true;
inline constexpr bool ranges::enable_safe_range<std::span<T, Extent>> = true;
+
 
}}
 
}}
This specialization of {{ltt|cpp/ranges/safe_range|std::ranges::enable_safe_range}} makes {{tt|span}} satisfy {{lconcept|safe_range}}.
+
This specialization of {{lc|ranges::enable_view}} makes {{tt|span}} satisfy {{lconcept|view}}.
  
 
==={{rl|deduction guides|Deduction guides}}===
 
==={{rl|deduction guides|Deduction guides}}===
  
{{langlinks|ja|zh}}
+
===Notes===
 +
Specializations of {{tt|std::span}} are already trivially copyable types in all existing implementations, even before the formal requirement introduced in C++23.
 +
 
 +
{{ftm begin|sort=yes}}
 +
{{ftm|__cpp_lib_span|std=C++20|value=202002L|{{tt|std::span}}|rowspan="2"}}
 +
{{ftm|-|std=C++26|value=202311L|{{lc|std::span::at}}}}
 +
{{ftm|__cpp_lib_span_initializer_list|value=202311L|std=C++26|Constructing {{tt|std::span}} from a {{lc|std::initializer_list}}}}
 +
{{ftm end}}
 +
 
 +
===Example===
 +
{{example
 +
|The example uses {{tt|std::span}} to implement some algorithms on contiguous ranges.
 +
|code=
 +
#include <algorithm>
 +
#include <cstddef>
 +
#include <iostream>
 +
#include <span>
 +
 
 +
template<class T, std::size_t N>
 +
[[nodiscard]]
 +
constexpr auto slide(std::span<T, N> s, std::size_t offset, std::size_t width)
 +
{
 +
    return s.subspan(offset, offset + width <= s.size() ? width : 0U);
 +
}
 +
 
 +
template<class T, std::size_t N, std::size_t M>
 +
constexpr bool starts_with(std::span<T, N> data, std::span<T, M> prefix)
 +
{
 +
    return data.size() >= prefix.size()
 +
        && std::equal(prefix.begin(), prefix.end(), data.begin());
 +
}
 +
 
 +
template<class T, std::size_t N, std::size_t M>
 +
constexpr bool ends_with(std::span<T, N> data, std::span<T, M> suffix)
 +
{
 +
    return data.size() >= suffix.size()
 +
        && std::equal(data.end() - suffix.size(), data.end(),
 +
                      suffix.end() - suffix.size());
 +
}
 +
 
 +
template<class T, std::size_t N, std::size_t M>
 +
constexpr bool contains(std::span<T, N> span, std::span<T, M> sub)
 +
{
 +
    return std::ranges::search(span, sub).begin() != span.end();
 +
}
 +
 
 +
void println(const auto& seq)
 +
{
 +
    for (const auto& elem : seq)
 +
        std::cout << elem << ' ';
 +
    std::cout << '\n';
 +
}
 +
 
 +
int main()
 +
{
 +
    constexpr int a[]{0, 1, 2, 3, 4, 5, 6, 7, 8};
 +
    constexpr int b[]{8, 7, 6};
 +
    constexpr static std::size_t width{6};
 +
 
 +
    for (std::size_t offset{}; ; ++offset)
 +
        if (auto s = slide(std::span{a}, offset, width); !s.empty())
 +
            println(s);
 +
        else
 +
            break;
 +
 
 +
    static_assert(""
 +
        && starts_with(std::span{a}, std::span{a, 4})
 +
        && starts_with(std::span{a + 1, 4}, std::span{a + 1, 3})
 +
        && !starts_with(std::span{a}, std::span{b})
 +
        && !starts_with(std::span{a, 8}, std::span{a + 1, 3})
 +
        && ends_with(std::span{a}, std::span{a + 6, 3})
 +
        && !ends_with(std::span{a}, std::span{a + 6, 2})
 +
        && contains(std::span{a}, std::span{a + 1, 4})
 +
        && !contains(std::span{a, 8}, std::span{a, 9})
 +
    );
 +
}
 +
|output=
 +
0 1 2 3 4 5
 +
1 2 3 4 5 6
 +
2 3 4 5 6 7
 +
3 4 5 6 7 8
 +
}}
 +
 
 +
===Defect reports===
 +
{{dr list begin}}
 +
{{dr list item|wg=lwg|dr=3203|std=C++20|before=it was unclear when the pointers, iterators, and<br>references to elements of {{tt|span}} are invalidated|after=made clear}}
 +
{{dr list item|wg=lwg|dr=3903|std=C++20|before=the declaration of {{tt|span}}'s destructor was unnecessary|after=removed the declaration}}
 +
{{dr list item|paper=P2325R3|std=C++20|before=a {{tt|span}} of non-zero static extents was not a {{tt|view}}|after=any {{tt|span}} is a {{tt|view}}}}
 +
{{dr list end}}
 +
 
 +
===See also===
 +
{{dsc begin}}
 +
{{dsc inc|cpp/container/dsc mdspan}}
 +
{{dsc inc|cpp/ranges/dsc subrange}}
 +
{{dsc inc|cpp/utility/dsc initializer_list}}
 +
{{dsc inc|cpp/string/dsc basic_string_view}}
 +
{{dsc end}}
 +
 
 +
{{langlinks|de|es|ja|ru|zh}}

Latest revision as of 08:41, 24 September 2024

 
 
 
 
Defined in header <span>
template<

    class T,
    std::size_t Extent = std::dynamic_extent

> class span;
(since C++20)

The class template span describes an object that can refer to a contiguous sequence of objects with the first element of the sequence at position zero. A span can either have a static extent, in which case the number of elements in the sequence is known at compile-time and encoded in the type, or a dynamic extent.

For a span s, pointers, iterators, and references to elements of s are invalidated when an operation invalidates a pointer in the range [s.data()s.data() + s.size()).

Every specialization of std::span is a TriviallyCopyable type.

(since C++23)

A typical implementation holds a pointer to T, if the extent is dynamic, the implementation also holds a size.

Contents

[edit] Template parameters

T - element type; must be a complete object type that is not an abstract class type
Extent - the number of elements in the sequence, or std::dynamic_extent if dynamic

[edit] Member types

Member type Definition
element_type T
value_type std::remove_cv_t<T>
size_type std::size_t
difference_type std::ptrdiff_t
pointer T*
const_pointer const T*
reference T&
const_reference const T&
iterator implementation-defined LegacyRandomAccessIterator, ConstexprIterator, and contiguous_iterator whose value_type is value_type
const_iterator (since C++23) std::const_iterator<iterator>
reverse_iterator std::reverse_iterator<iterator>
const_reverse_iterator (since C++23) std::const_iterator<reverse_iterator>

Note: iterator is a mutable iterator if T is not const-qualified.

All requirements on the iterator types of a Container apply to the iterator type of span as well.

[edit] Member constant

Name Value
constexpr std::size_t extent
[static]
Extent
(public static member constant)

[edit] Member functions

constructs a span
(public member function) [edit]
assigns a span
(public member function) [edit]
(destructor)
(implicitly declared)
destructs a span
(public member function)
Iterators
returns an iterator to the beginning
(public member function) [edit]
(C++23)
returns an iterator to the end
(public member function) [edit]
returns a reverse iterator to the beginning
(public member function) [edit]
(C++23)
returns a reverse iterator to the end
(public member function) [edit]
Element access
access the first element
(public member function) [edit]
access the last element
(public member function) [edit]
(C++26)
access specified element with bounds checking
(public member function) [edit]
access specified element
(public member function) [edit]
direct access to the underlying contiguous storage
(public member function) [edit]
Observers
returns the number of elements
(public member function) [edit]
returns the size of the sequence in bytes
(public member function) [edit]
checks if the sequence is empty
(public member function) [edit]
Subviews
obtains a subspan consisting of the first N elements of the sequence
(public member function) [edit]
obtains a subspan consisting of the last N elements of the sequence
(public member function) [edit]
obtains a subspan
(public member function) [edit]

[edit] Non-member functions

converts a span into a view of its underlying bytes
(function template) [edit]

[edit] Non-member constant

a constant of type std::size_t signifying that the span has dynamic extent
(constant) [edit]

[edit] Helper templates

template< class T, std::size_t Extent >
constexpr bool ranges::enable_borrowed_range<std::span<T, Extent>> = true;
(since C++20)

This specialization of ranges::enable_borrowed_range makes span satisfy borrowed_range.

template< class T, std::size_t Extent >
constexpr bool ranges::enable_view<std::span<T, Extent>> = true;
(since C++20)

This specialization of ranges::enable_view makes span satisfy view.

[edit] Deduction guides

[edit] Notes

Specializations of std::span are already trivially copyable types in all existing implementations, even before the formal requirement introduced in C++23.

Feature-test macro Value Std Feature
__cpp_lib_span 202002L (C++20) std::span
202311L (C++26) std::span::at
__cpp_lib_span_initializer_list 202311L (C++26) Constructing std::span from a std::initializer_list

[edit] Example

The example uses std::span to implement some algorithms on contiguous ranges.

#include <algorithm>
#include <cstddef>
#include <iostream>
#include <span>
 
template<class T, std::size_t N>
[[nodiscard]]
constexpr auto slide(std::span<T, N> s, std::size_t offset, std::size_t width)
{
    return s.subspan(offset, offset + width <= s.size() ? width : 0U);
}
 
template<class T, std::size_t N, std::size_t M>
constexpr bool starts_with(std::span<T, N> data, std::span<T, M> prefix)
{
    return data.size() >= prefix.size()
        && std::equal(prefix.begin(), prefix.end(), data.begin());
}
 
template<class T, std::size_t N, std::size_t M>
constexpr bool ends_with(std::span<T, N> data, std::span<T, M> suffix)
{
    return data.size() >= suffix.size()
        && std::equal(data.end() - suffix.size(), data.end(),
                      suffix.end() - suffix.size());
}
 
template<class T, std::size_t N, std::size_t M>
constexpr bool contains(std::span<T, N> span, std::span<T, M> sub)
{
    return std::ranges::search(span, sub).begin() != span.end();
}
 
void println(const auto& seq)
{
    for (const auto& elem : seq)
        std::cout << elem << ' ';
    std::cout << '\n';
}
 
int main()
{
    constexpr int a[]{0, 1, 2, 3, 4, 5, 6, 7, 8};
    constexpr int b[]{8, 7, 6};
    constexpr static std::size_t width{6};
 
    for (std::size_t offset{}; ; ++offset)
        if (auto s = slide(std::span{a}, offset, width); !s.empty())
            println(s);
        else
            break;
 
    static_assert(""
        && starts_with(std::span{a}, std::span{a, 4})
        && starts_with(std::span{a + 1, 4}, std::span{a + 1, 3})
        && !starts_with(std::span{a}, std::span{b})
        && !starts_with(std::span{a, 8}, std::span{a + 1, 3})
        && ends_with(std::span{a}, std::span{a + 6, 3})
        && !ends_with(std::span{a}, std::span{a + 6, 2})
        && contains(std::span{a}, std::span{a + 1, 4})
        && !contains(std::span{a, 8}, std::span{a, 9})
    );
}

Output:

0 1 2 3 4 5
1 2 3 4 5 6
2 3 4 5 6 7
3 4 5 6 7 8

[edit] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 3203 C++20 it was unclear when the pointers, iterators, and
references to elements of span are invalidated
made clear
LWG 3903 C++20 the declaration of span's destructor was unnecessary removed the declaration
P2325R3 C++20 a span of non-zero static extents was not a view any span is a view

[edit] See also

(C++23)
a multi-dimensional non-owning array view
(class template) [edit]
combines an iterator-sentinel pair into a view
(class template) [edit]
references a temporary array created in list-initialization
(class template) [edit]
read-only string view
(class template) [edit]