How do I construct and use std::span in C++?

In C++, std::span is a lightweight proxy object that provides a view over a contiguous sequence of elements, available in C++20. It allows you to operate on arrays and other sequences without having to pass pointers and sizes separately. This can improve code readability and safety.

Here’s how to construct and use std::span in your C++ code:

#include #include #include void printSpan(std::span s) { for (int i : s) { std::cout << i << " "; } std::cout << std::endl; } int main() { // Using std::array std::array arr = {1, 2, 3, 4, 5}; std::span span1 = arr; // Span over std::array printSpan(span1); // Using std::vector std::vector vec = {6, 7, 8, 9, 10}; std::span span2 = vec; // Span over std::vector printSpan(span2); // Using raw arrays int rawArray[] = {11, 12, 13, 14, 15}; std::span span3(rawArray, 5); // Span over raw array printSpan(span3); return 0; }

C++ std::span C++20 programming arrays pointers sequences