std::span<T,Extent>::first
From cppreference.com
template< std::size_t Count >
constexpr std::span<element_type, Count> first() const;
|
(1) | (since C++20) |
constexpr std::span<element_type, std::dynamic_extent>
first( size_type count ) const;
|
(2) | (since C++20) |
Obtains a subview over the first Count or count elements of this span.
1) The element count is provided as a template argument, and the subview has a static extent.
If
Count > Extent is true, the program is ill-formed.2) The element count is provided as a function argument, and the subview has a dynamic extent.
|
If |
(until C++26) |
|
If
|
(since C++26) |
Parameters
| count | - | the number of the elements of the subview |
Return value
1)
std::span<element_type, Count>(data(), Count)2)
std::span<element_type, std::dynamic_extent>(data(), count)Example
Run this code
#include <print>
#include <ranges>
#include <span>
void run_game(std::span<const int> span)
{
std::println("span[{}] = {}", std::size(span), span);
std::span<const int, 5> span_first = span.first<5>();
std::println("span.first<5>() = {}", span_first);
std::span<const int, std::dynamic_extent> span_first_dynamic = span.first(4);
std::println("span.first(4) = {}", span_first_dynamic);
}
int main()
{
int a[8]{1, 2, 3, 4, 5, 6, 7, 8};
std::println("int a[{}] = {}", std::size(a), a);
run_game(a);
}
Output:
int a[8] = [1, 2, 3, 4, 5, 6, 7, 8]
span[8] = [1, 2, 3, 4, 5, 6, 7, 8]
span.first<5>() = [1, 2, 3, 4, 5]
span.first(4) = [1, 2, 3, 4]
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 4293 | C++20 | the returned std::span was direct-list-initialized
|
it is direct-non-list-initialized |
See also
obtains a subspan consisting of the last N elements of the sequence (public member function) | |
| obtains a subspan (public member function) |