命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | container‎ | span
template< std::size_t Count >
constexpr std::span<element_type, Count> first() const;
(since C++20)
constexpr std::span<element_type, std::dynamic_extent> first( size_type Count ) const;
(since C++20)

获得一个 span,它是此 span 的前 Count 个元素的视图。如果 Count > Extent,则程序是非良构的。如果 Count > size(),则行为未定义。

[编辑] 返回值

span r,它是 *this 的前 Count 个元素的视图,使得 r.data() == this->data() && r.size() == Count

[编辑] 示例

#include <iostream>
#include <ranges>
#include <span>
#include <string_view>
 
void print(std::string_view const title,
           std::ranges::forward_range auto const& container)
{
    auto size{std::size(container)};
    std::cout << title << '[' << size << "]{";
    for (auto const& 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};

[编辑] 参见

获得一个子 span,包含序列的最后 N 个元素
(public member function) [编辑]
获得一个子 span
(public member function) [编辑]