Is it possible to get a sub-array of a std::array in C++?

Viewed 5952

I would like to do something like

std::array<int, 5> array1 = {{ ... }};
const std::array<int, 3>& array2 = array1[1:4]; // [x:y] doesn't exist

That is, get an array that is a sort of view of another array, without having to copy it.

4 Answers

Yes you can, std::span in C++20 provides a view over a contiguous sequence of objects.

std::array<int, 5> array1 = {20, 10, 35, 30, 5};
std::span array2(array1.begin(), array1.begin() + 3); // {20, 10, 35}; subview of array1

The underlying data is not copied but rather referenced, therefore care should be taken to ensure the original array still exists when using the span.

Related