Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

stl

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.

like image 910
Ant6n Avatar asked Mar 16 '16 20:03

Ant6n


People also ask

How do you pass an array Subarray?

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.

What is sub array of an array?

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).

How do you pass a sub array to a function in C++?

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.


2 Answers

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

like image 22
Slava Avatar answered Oct 23 '22 02:10

Slava


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).

like image 107
Brian Bi Avatar answered Oct 23 '22 04:10

Brian Bi