0Pricing
C++ Academy · Lesson

std::span Basics

Non-owning views over contiguous data.

A Non-Owning View

std::span<T> (C++20) is a lightweight view over a contiguous sequence, like string_view but for any element type. Include <span>.

#include <iostream>
#include <span>
#include <array>
int main() {
    std::array<int, 3> a = {1, 2, 3};
    std::span<int> s = a;
    std::cout << s.size() << "\n";
}

Spans Do Not Own

A span stores a pointer and a length; it observes data owned elsewhere and never copies the elements.

#include <iostream>
#include <vector>
#include <span>
int main() {
    std::vector<int> v = {5, 6, 7};
    std::span<int> s = v;
    s[0] = 50; // modifies v
    std::cout << v[0] << "\n"; // 50
}

All lessons in this course

  1. Fixed-Size std::array
  2. std::span Basics
  3. Passing Spans to Functions
  4. Bounds and Subspans
← Back to C++ Academy