std::span subspan() method
- since C++20
// (1) Const version only
template< std::size_t Offset,
std::size_t Count = std::dynamic_extent >
constexpr std::span<element_type, E /* see below */> subspan() const;
// (2) Const version only
constexpr std::span<element_type, std::dynamic_extent>
subspan( size_type Offset,
size_type Count = std::dynamic_extent ) const;
Obtains a span that is a view over the Count
elements of this
span starting at offset Offset
.
If Count
is std::dynamic_extent
, the number of elements in the subspan is size() - offset
(i.e., it ends at the end of *this
).
The extent E
of the span returned by (1) is determined as follows:
- If
Count
is not std::dynamic_extent -Count
; - Otherwise, if
Extent
is notstd::dynamic_extent
-Extent - Offset
; - Otherwise -
std::dynamic_extent
.
important
(1) is ill-formed if:
Offset > Extent
, orCount
is notstd::dynamic_extent
andCount > Extent - Offset
.
Undefined Behaviour
The behavior is undefined if either Offset
or Count
is out of range.
This happens if:
Offset
is greater thansize()
, orCount
is notstd::dynamic_extent
andCount
is greater thansize() - Offset
Parameters
- (2)
Count
- the number of the elements to make a span ofOffset
- offset to start from
Return value
A span s
that is a view over the subspan Count
elements of *this
, with the following properties:
s.data() == this->data() + Offset
and- If
Count
isstd::dynamic_extent
:s.size() == this->size() - Offset
- Otherwise
s.size() == Count
Complexity
Constant - O(1).
Exceptions
(none)
Example
Main.cpp
#include <algorithm>
#include <cstdio>
#include <numeric>
#include <ranges>
#include <span>
void display(std::span<const char> abc)
{
const auto columns{ 20U };
const auto rows{ abc.size() - columns + 1 };
for (auto offset{ 0U }; offset < rows; ++offset) {
std::ranges::for_each(
abc.subspan(offset, columns),
std::putchar
);
std::putchar('\n');
}
}
int main()
{
char abc[26];
std::iota(std::begin(abc), std::end(abc), 'A');
display(abc);
}
Output
ABCDEFGHIJKLMNOPQRST
BCDEFGHIJKLMNOPQRSTU
CDEFGHIJKLMNOPQRSTUV
DEFGHIJKLMNOPQRSTUVW
EFGHIJKLMNOPQRSTUVWX
FGHIJKLMNOPQRSTUVWXY
GHIJKLMNOPQRSTUVWXYZ
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.
Hover to see the original license.