std::span first() 方法
- 自 C++20 起
// (1) Const version only
template< std::size_t Count >
constexpr std::span<element_type, Count> first() const;
// (2) Const version only
constexpr std::span<element_type, std::dynamic_extent> first( size_type Count ) const;
获取一个 span,它是此 span 前 Count
个元素的视图。
重要
如果 Count > Extent
,则程序格式错误。
Count > Extent
。未定义行为
行为未定义
如果Count > size()
。参数
- (2) -
Count
- 构成 span 的元素数量
返回值
一个 span s
,它是 *this
的前 Count
个元素的视图,具有以下属性
s.data() == this->data()
s.size() == Count
复杂度
常数 - O(1)。
异常
(无)
示例
Main.cpp
#include <iostream>
#include <span>
#include <string_view>
void print(std::string_view const title,
/* std::ranges::forward_range */ auto const& container) {
std::cout << title << "[" << std::size(container) << "]{ ";
for (auto const& elem : container)
std::cout << elem << ", ";
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, };