Namespaces
Variants

std::span<T,Extent>:: first

From cppreference.net
template < std:: size_t Count >
constexpr std:: span < element_type, Count > first ( ) const ;
(1) (自 C++20 起)
constexpr std:: span < element_type, std:: dynamic_extent >
first ( size_type count ) const ;
(2) (自 C++20 起)

获取此 span 前 Count count 个元素的子视图。

1) 元素数量通过模板参数提供,且该子视图具有静态范围。
如果 Count > Extent true ,则程序是非良构的。
2) 元素数量通过函数参数提供,且该子视图具有动态范围。

Count > size ( ) count > size ( ) true ,则行为未定义。

(C++26 前)

Count > size ( ) count > size ( ) true

  • 若实现为 强化实现 ,则发生 契约违反 。此外,若契约违反处理程序在“观察”评估语义下返回,则行为未定义。
  • 若实现非强化实现,则行为未定义。
(C++26 起)

目录

参数

count - 子视图的元素数量

返回值

1) std:: span < element_type, Count > { data ( ) , Count }
2) std:: span < element_type, std:: dynamic_extent > { data ( ) , count }

示例

#include <iostream>
#include <ranges>
#include <span>
#include <string_view>
void print(const std::string_view title,
           const std::ranges::forward_range auto& container)
{
    auto size{std::size(container)};
    std::cout << title << '[' << size << "]{";
    for (const auto& elem : container)
        std::cout << elem << (--size ? ", " : "");
    std::cout << "};\n";
}
void run_game(std::span<const int> span)
{
    print("span: ", span);
    std::span<const int, 5> span_first = span.first<5>();
    print("span.first<5>(): ", span_first);
    std::span<const int, std::dynamic_extent> span_first_dynamic = span.first(4);
    print("span.first(4): ", span_first_dynamic);
}
int main()
{
    int a[8]{1, 2, 3, 4, 5, 6, 7, 8};
    print("int a", a);
    run_game(a);
}

输出:

int a[8]{1, 2, 3, 4, 5, 6, 7, 8};
span: [8]{1, 2, 3, 4, 5, 6, 7, 8};
span.first<5>(): [5]{1, 2, 3, 4, 5};
span.first(4): [4]{1, 2, 3, 4};

参见

获取由序列末尾 N 个元素组成的子跨度
(公开成员函数)
获取子跨度
(公开成员函数)