Site Tools


wiki:hpp-span

Table of Contents

<span>

<span> is a non-owning view over a contiguous range of elements (C++20): it holds a pointer and length, allowing you to pass array data without copying. Use it as a function parameter to accept any contiguous container.

It's like a safer const T* / size_t pair.

Example

This example passes both vector and C-array data to the same function via span, demonstrating generic array viewing.

// compile: g++ -std=c++20 -o spanexample spanexample.cpp
// run: ./spanexample
// description: span as a generic array view
 
#include <span>
#include <vector>
#include <iostream>
 
void print_span(std::span<const int> s) {
    for (int x : s) std::cout << x << " ";
    std::cout << "\n";
}
 
int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    print_span(v);
 
    int arr[] = {10, 20, 30};
    print_span(arr);
 
    return 0;
}
wiki/hpp-span.md · Last modified: by 127.0.0.1