Ant6n
Ant6n

Reputation: 2007

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

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.

Upvotes: 11

Views: 8776

Answers (4)

Hugo
Hugo

Reputation: 404

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.

Upvotes: 2

Slava
Slava

Reputation: 1524

You can if you use valarray instead of array http://en.cppreference.com/w/cpp/numeric/valarray/slice

Edit: from C++20 you can refer to a continuous sub-array with std::span

Upvotes: 5

Brian Bi
Brian Bi

Reputation: 119099

No, you can't do that. All standard library containers are unique owners of their data, and std::array is no exception. In fact, std::array is constrained to be implemented in such a way so that the elements are stored inside an actual array member of the class, which would make aliasing impossible.

There is a proposal for an array_view class that would represent a non-owning view into a contiguous block of data. You can read about it here. I don't know the status of this proposal (the current C++ standardization process confuses me).

Upvotes: 6

Bartosz Bosowiec
Bartosz Bosowiec

Reputation: 171

std::array<int, 3>& array2 = reinterpret_cast<std::array<int, 3>&>(array1);

Upvotes: -5

Related Questions