Reputation: 2007
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
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
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
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
Reputation: 171
std::array<int, 3>& array2 = reinterpret_cast<std::array<int, 3>&>(array1);
Upvotes: -5