命名空间
变体
操作

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

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

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

[编辑] 返回值

一个跨度 r,它是 *this 的最后 Count 个元素的视图,满足 r.data() == this->data() + (this->size() - Count) && r.size() == Count

[编辑] 示例

#include <iostream>
#include <span>
#include <string_view>
 
void println(std::string_view const title, auto const& container)
{
    std::cout << title << '[' << std::size(container) << "]{ ";
    for (auto const& elem : container)
        std::cout << elem << ", ";
    std::cout << "};\n";
};
 
void run(std::span<const int> span)
{
    println("span: ", span);
 
    std::span<const int, 3> span_last = span.last<3>();
    println("span.last<3>(): ", span_last);
 
    std::span<const int, std::dynamic_extent> span_last_dynamic = span.last(2);
    println("span.last(2): ", span_last_dynamic);
}
 
int main()
{
    int a[8]{1, 2, 3, 4, 5, 6, 7, 8};
    println("int a", a);
    run(a);
}

输出

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

[编辑] 参见

获得一个由序列的前 N 个元素组成的子跨度
(公开成员函数) [编辑]
获得一个子跨度
(公开成员函数) [编辑]