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

来自cppreference.com
< 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 起)

获得此 span 的后 Countcount 个元素上的子视图。

1) 元素个数由模板实参提供,并且子视图拥有静态长度。
如果 Count > Extenttrue,那么程序非良构。
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 个元素组成的子段
(公开成员函数)
获得子段
(公开成员函数)