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
- Fixed-Size std::array
- std::span Basics
- Passing Spans to Functions
- Bounds and Subspans