Nostalgic
Nostalgic

Reputation: 310

Reference to a subarray within an array

I was trying to figure out how can I create sub arrays from within a larger array and got a piece of code here and started using it.

I created an array of ints

int arr[10];
for(int h=0;h<10;h++)
{
    arr[h]=20+h;
}

Now say I want a sub-array (of 4 ints) within the same larger array

int (&arrOnly4Elements)[4]=(int (&)[4])(*arr);

It works well and does what I want. While I understand references and that they point to actual objects, What I am not able to understand how the above code works. why do we need the braces to surround &arrOnly4Elements Also, can anyone explain me the RHS (int (&)[4])(*arr); in detail step by step manner.

Upvotes: 1

Views: 850

Answers (1)

Werner Henze
Werner Henze

Reputation: 16726

cdecl.org translates it for you:

int (&arrrOnly4Elements)[4]: declare arrrOnly4Elements as reference to array 4 of int

int &arrrOnly4Elements[4]: declare arrrOnly4Elements as array 4 of reference to int

As NathanOliver pointed out, C++20 introduces std::span. You should take a look at it (also compare this SO question). A std::span is a templated view into an array/contiguous sequence of objects. It consists of a pointer and a size. It makes accessing arrays and sub arrays convenient (allows range based for) and safe (keeps track of the size).

int arr[10];
std::span<int> arr_span = arr;
std::span<int,4> arr_subspan1 = arr_span.first<4>();
std::span<int> arr_subspan2 = arr_span.first(4);

If you cannot yet switch to C++20 you might consider checking GSL which provides a gsl::span which was lately aligned to match std::span.

Upvotes: 1

Related Questions