0Pricing
C++ Academy · Lesson

Bounds and Subspans

Slice spans safely.

Slicing with subspan

s.subspan(offset, count) returns a span over part of the original, no copy, just a new pointer and length.

#include <iostream>
#include <span>
int main() {
    int buf[] = {0, 1, 2, 3, 4};
    std::span<int> s(buf, 5);
    auto mid = s.subspan(1, 3);
    for (int x : mid) std::cout << x << " ";
    std::cout << "\n"; // 1 2 3
}

first and last

first(n) and last(n) give spans over the leading or trailing n elements.

#include <iostream>
#include <span>
int main() {
    int buf[] = {10, 20, 30, 40};
    std::span<int> s(buf, 4);
    auto f = s.first(2);
    auto l = s.last(2);
    std::cout << f[0] << " " << l[1] << "\n"; // 10 40
}

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