Namespaces
Variants

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

From cppreference.net
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 起)

获取此 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 ( ) + ( size ( ) - Count ) , Count }
2) std:: span < element_type, std:: dynamic_extent > { data ( ) + ( size ( ) - count ) , count }

示例

#include <iostream>
#include <span>
#include <string_view>
void println(const std::string_view title, const auto& container)
{
    std::cout << title << '[' << std::size(container) << "]{ ";
    for (const auto& 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 个元素组成的子跨度
(公开成员函数)
获取子跨度
(公开成员函数)