std::span<T,Extent>::first
來自 cppreference.com
template< std::size_t Count > constexpr std::span<element_type, Count> first() const; |
(C++20 起) | |
constexpr std::span<element_type, std::dynamic_extent> first( size_type Count ) const; |
(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};
[編輯] 參閱
獲取由序列後 N 個元素組成的子 span(public member function) | |
獲取一個子 span (public member function) |