0
0
CppConceptBeginner · 3 min read

What is span in C++: Simple Explanation and Example

std::span in C++ is a lightweight view over a continuous sequence of elements like arrays or vectors without owning them. It allows safe and easy access to a range of elements without copying data.
⚙️

How It Works

std::span acts like a window that looks at a part of an array or container without owning the data itself. Imagine you have a photo album, and you want to show a few pictures to a friend without giving them the whole album. std::span lets you point to just those pictures without making a copy.

It stores a pointer to the first element and the number of elements it covers. This means you can safely access elements in that range, and the original data stays unchanged. Since it does not own the data, it is very fast and uses little memory.

💻

Example

This example shows how to create a std::span from an array and use it to print elements.

cpp
#include <iostream>
#include <span>

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    std::span<int> view(numbers, 3); // View first 3 elements

    for (int num : view) {
        std::cout << num << ' ';
    }
    std::cout << '\n';
    return 0;
}
Output
10 20 30
🎯

When to Use

Use std::span when you want to pass or work with a part of an array or container without copying it. It is helpful in functions that need to read or modify a sequence of elements safely and efficiently.

For example, if you have a large array and want to process only a slice of it, std::span lets you do that without extra memory or copying. It is also useful for APIs that accept any continuous data like arrays, vectors, or C-style arrays in a uniform way.

Key Points

  • std::span is a non-owning view over contiguous data.
  • It stores a pointer and size to represent a range.
  • It avoids copying data, making it efficient.
  • Works with arrays, vectors, and other contiguous containers.
  • Introduced in C++20 for safer and easier data access.

Key Takeaways

std::span provides a safe, efficient way to view parts of arrays or containers without copying.
It stores a pointer and size but does not own the data it points to.
Use it to pass slices of data to functions or work with subranges easily.
Introduced in C++20, it improves code clarity and performance for continuous data access.