cpp / expert
Snippet
Contiguous Data Views with std::span
std::span (C++20) provides a non-owning view over a contiguous sequence of objects. It abstracts away the container type (array, vector, etc.) while maintaining performance and providing bounds-safe access, making it the modern standard for passing arrays to functions.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <span>#include <vector>#include <iostream>void process_buffer(std::span<const int> data) {for (const auto& val : data) {std::cout << val << " ";}}int main() {int arr[] = {1, 2, 3};std::vector<int> vec = {4, 5, 6};process_buffer(arr);process_buffer(vec);process_buffer({vec.data(), 2}); // Subspan}
Breakdown
1
void process_buffer(std::span<const int> data)
Accepts any contiguous memory block without copying or template bloat.
2
process_buffer(arr);
Automatically deduces the size of the raw C-style array.
3
process_buffer({vec.data(), 2});
Creates a subview of the first two elements without memory allocation.