0 day streak
cpp / intermediate
Snippet

Contiguous Memory Views with Spans

std::span (C++20) is a non-owning view over a contiguous sequence of objects. It allows functions to accept arrays, vectors, or raw pointers interchangeably without copying data or losing size information, significantly improving performance and flexibility.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <span>
#include <vector>
void print_data(std::span<int> view) {
for (int x : view) {
std::cout << x << " ";
}
std::cout << std::endl;
}
int main() {
int raw_arr[] = {1, 2, 3};
std::vector<int> vec = {4, 5, 6};
print_data(raw_arr); // Works with raw arrays
print_data(vec); // Works with vectors
return 0;
}
Breakdown
1
void print_data(std::span<int> view)
Accepts a 'view' that can point to any contiguous memory source.