C++20 std::span:非拥有型数组视图
学习使用span作为连续序列的轻量级抽象,避免指针和数组退化问题。 · 难度:入门 · +15XP
什么是std::span?
std::span是一个非拥有型视图,可以引用连续的序列(数组、std::vector、C风格数组等)。它类似于std::string_view但用于任意类型。
基本用法
#include <span>
#include <vector>
#include <iostream>
void print(std::span<int> s) {
for (int i : s)
std::cout << i << ' ';
std::cout << '
';
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
std::vector<int> vec = {10, 20, 30};
print(arr); // 自动推导大小
print(vec);
print({arr + 1, 3}); // 手动指定子范围
}
span的特性
| 特性 | 说明 |
|---|---|
| 非拥有 | 不管理内存生命周期 |
| 可复制 | 轻量级拷贝 |
| 边界安全 | 运行时边界检查(可选) |
| 兼容性 | 接受数组、vector、initializer_list |
动态扩展与子视图
std::span<int> full(vec);
auto first_half = full.first(2); // 前两个元素
auto last = full.last(1); // 最后一个元素
auto mid = full.subspan(1, 2); // 从索引1开始的两个元素与函数参数
使用std::span代替C风格指针+大小参数,提高代码安全性和可读性。
练习提示
编写一个函数sum,接受一个std::span<int>并返回元素总和。然后在main中用数组、vector和子span测试。