跳转至

span

  • std::span 是 C++ 中引入的一种容器视图类型(联想到string_view)。它提供了对现有数组或容器的非拥有权(non-owning)引用,允许你以容器视图的方式操作底层数据,而无需复制或分配内存。
  • span 能拥有静态长度,此时序列中的元素数在编译期已知并在类型中编码,也可以拥有动态长度。如果 span 拥有动态长度,那它的典型实现会有两个成员:一个指向 T 的指针和一个长度。 具有静态长度的 span 可能只有一个成员指向 T 的指针。
  • std::span 可以用于数组、标准数组、std::vectorstd::array 等,提供了一个轻量级的方式来处理和传递连续内存区域的引用。这对于传递函数参数、迭代和访问数据而言非常方便。

示例

#include <iostream>
#include <vector>
#include <span>

void printNumbers(std::span<int> numbers) {
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
}

int main() {
    // Using std::vector as an example container
    std::vector<int> numbers = {1, 2, 3, 4, 5};

    // Creating a std::span to view the content of the vector
    std::span<int> numbersView(numbers);

    // Passing the span to a function
    printNumbers(numbersView);

    // Modifying the vector through the span
    numbersView[2] = 10;

    // Outputting the modified vector
    printNumbers(numbersView);

    return 0;
}