跳到主要内容

std::span last() 方法

// (1) Const version only
template< std::size_t Count >
constexpr std::span<element_type, Count> last() const;

// (2) Const version only
constexpr std::span<element_type, std::dynamic_extent> last( size_type Count ) const;

获取一个 span,它是一个视图,包含此 span 的最后 Count 个元素。

重要

如果 Count > Extent,则程序格式错误

如果 Count > Extent

未定义行为

行为未定义

如果 Count > size()

参数

  • (2) - Count - 要构成 span 的元素数量

返回值

一个 span s,它是 *this 的最后 Count 个元素的视图,具有以下属性:

  • s.data() == this->data() + (this->size() - Count)
  • s.size() == Count

复杂度

常数 - O(1)

异常

(无)

示例

Main.cpp
#include <iostream>
#include <span>
#include <string_view>

auto print = [](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)
{
print("span: ", span);

std::span<const int, 3> span_last = span.last<3>();
print("span.last<3>(): ", span_last);

std::span<const int, std::dynamic_extent> span_last_dynamic = span.last(2);
print("span.last(2): ", span_last_dynamic);
}

int main()
{
int a[8]{ 1, 2, 3, 4, 5, 6, 7, 8, };
print("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, };
本文来源于此 CppReference 页面。它可能为了改进或编辑者的偏好而进行了修改。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。

std::span last() 方法

// (1) Const version only
template< std::size_t Count >
constexpr std::span<element_type, Count> last() const;

// (2) Const version only
constexpr std::span<element_type, std::dynamic_extent> last( size_type Count ) const;

获取一个 span,它是一个视图,包含此 span 的最后 Count 个元素。

重要

如果 Count > Extent,则程序格式错误

如果 Count > Extent

未定义行为

行为未定义

如果 Count > size()

参数

  • (2) - Count - 要构成 span 的元素数量

返回值

一个 span s,它是 *this 的最后 Count 个元素的视图,具有以下属性:

  • s.data() == this->data() + (this->size() - Count)
  • s.size() == Count

复杂度

常数 - O(1)

异常

(无)

示例

Main.cpp
#include <iostream>
#include <span>
#include <string_view>

auto print = [](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)
{
print("span: ", span);

std::span<const int, 3> span_last = span.last<3>();
print("span.last<3>(): ", span_last);

std::span<const int, std::dynamic_extent> span_last_dynamic = span.last(2);
print("span.last(2): ", span_last_dynamic);
}

int main()
{
int a[8]{ 1, 2, 3, 4, 5, 6, 7, 8, };
print("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, };
本文来源于此 CppReference 页面。它可能为了改进或编辑者的偏好而进行了修改。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。