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.
You cannot pass an array to a function. When you try to, you actually pass the address of the first element of the array. If you need a subarray that starts at 5, you just pass the address of the fifth elements. You shouldn't be using C-style arrays anyway.
A subarray is a contiguous part of array. An array that is inside another array. For example, consider the array [1, 2, 3, 4], There are 10 non-empty sub-arrays. The subarrays are (1), (2), (3), (4), (1,2), (2,3), (3,4), (1,2,3), (2,3,4) and (1,2,3,4).
Passing one-dimensional arrays to functions The general syntax for passing an array to a function in C++ is: FunctionName (ArrayName); In this example, our program will traverse the array elements.
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With