Slicing std::array

c++ slice std vector
c++ array
std::array to c array
std matrix
std::array size
std::array copy

Is there an easy way to get a slice of an array in C++?

I.e., I've got

array<double, 10> arr10;

and want to get array consisting of five first elements of arr10:

array<double, 5> arr5 = arr10.???

(other than populating it by iterating through first array)

The constructors for std::array are implicitly defined so you can't initialize it with a another container or a range from iterators. The closest you can get is to create a helper function that takes care of the copying during construction. This allows for single phase initialization which is what I believe you're trying to achieve.

template<class X, class Y>
X CopyArray(const Y& src, const size_t size)
    X dst;
    std::copy(src.begin(), src.begin() + size, dst.begin());
    return dst;
std::array<int, 5> arr5 = CopyArray<decltype(arr5)>(arr10, 5);

You can also use something like std::copy or iterate through the copy yourself.

std::copy(arr10.begin(), arr10.begin() + 5, arr5.begin());

std::slice_array is a helper template used by std::slice subscript operator. It has reference semantics to a subset of the array specified by the  std::slice is the selector class that identifies a subset of std::valarray. An object of type std::slice holds three values: the starting index, the stride, and the total number of values in the subset. Objects of type std::slice can be used as indexes with valarray’s operator[]. class slice; In simple terms it is used to slice based on an index.

Sure. Wrote this:

template<int...> struct seq {};
template<typename seq> struct seq_len;
template<int s0,int...s>
struct seq_len<seq<s0,s...>>:
    std::integral_constant<std::size_t,seq_len<seq<s...>>::value> {};
struct seq_len<seq<>>:std::integral_constant<std::size_t,0> {};
template<int Min, int Max, int... s>
struct make_seq: make_seq<Min, Max-1, Max-1, s...> {};
template<int Min, int... s>
struct make_seq<Min, Min, s...> {
  typedef seq<s...> type;
template<int Max, int Min=0>
using MakeSeq = typename make_seq<Min,Max>::type;

template<std::size_t src, typename T, int... indexes>
std::array<T, sizeof...(indexes)> get_elements( seq<indexes...>, std::array<T, src > const& inp ) {
  return { inp[indexes]...  };
template<int len, typename T, std::size_t src>
auto first_elements( std::array<T, src > const& inp )
  -> decltype( get_elements( MakeSeq<len>{}, inp ) )
  return get_elements( MakeSeq<len>{}, inp  );

Where the compile time indexes... does the remapping, and MakeSeq makes a seq from 0 to n-1.

Live example.

This supports both an arbitrary set of indexes (via get_elements) and the first n (via first_elements).


std::array< int, 10 > arr = {0,1,2,3,4,5,6,7,8,9};
std::array< int, 6 > slice = get_elements(arr, seq<2,0,7,3,1,0>() );
std::array< int, 5 > start = first_elements<5>(arr);

which avoids all loops, either explicit or implicit.

std::slice is the selector class that identifies a subset of std::valarray. An object of type This constructor exists only to allow construction of arrays of slices. This class is used as an intermediate type returned by valarray's subscript operator when used with slices. It references the elements in the valarray object that are selected by the slice, and overloads the assignment and compound assignment operators, allowing direct access to the elements in the selection.

2018 update, if all you need is first_elements:

Less boilerplaty solution using C++14 (building up on Yakk's pre-14 answer and stealing from "unpacking" a tuple to call a matching function pointer)

template < std::size_t src, typename T, int... I >
std::array< T, sizeof...(I) > get_elements(std::index_sequence< I... >, std::array< T, src > const& inp)
    return { inp[I]... };
template < int N, typename T, std::size_t src >
auto first_elements(std::array<T, src > const& inp)
    -> decltype(get_elements(std::make_index_sequence<N>{}, inp))
    return get_elements(std::make_index_sequence<N>{}, inp);

Still cannot explain why this works, but it does (for me on Visual Studio 2017).

It references the elements in the valarray object that are selected by the slice , and foo[std::slice (0,3,3)] = 99; // v v v // 99 10 2 99 4 50 99 7 8 std::cout​  Slick slicing for std::array's in C++. Contribute to Erikvv/array-slicing-cpp development by creating an account on GitHub.

Characteristics of the two reversal algorithms; n denotes the size of the input and S the size of a slice used by cpshtl::sliced array; – means that std::vector does  std::slice is the selector class that identifies a subset of std::valarray similar to BLAS slice. An object of type std::slice holds three values: the starting index, the stride, and the total number of values in the subset.

Used by slice. for this example, std::vector creates an array of pointers which point to 7 Feb 2006 Native C++ arrays (i. If there are no elements, the behavior is​  std.array. Functions and types that manipulate built-in arrays and associative arrays. slice and replacement do not need to be the same length. The result will

Instead, subscripting a valarray is defined to be the way to create a slice array corresponding to a given slice: template <class T2 class std::valarray { public: // in​  std::array is a container that encapsulates fixed size arrays. This container is an aggregate type with the same semantics as a struct holding a C-style array T[N] as its only non-static data member. Unlike a C-style array, it doesn't decay to T* automatically. As an aggregate type, it can be initialized with aggregate-initialization given at

Defaults to pointer to a void(T*, std::size_t) function, where first is array pointer and second auto slice(std::size_t begin) const -> StaticArrayView<size, const T​>. A slice is a segment of an array (dynamic or otherwise) that tracks both the pointer and the length of the segment. With the combined protection of having the length of the data, and the garbage collector to manage the memory backing the data, slices are an extremely powerful, dynamic concept that is safe from most memory corruption issues.

  • A pair of iterators is the closest C++ has to a slice. Something like Boost.Range does allow you to pack them together into one slice-like object, too.
  • Wow, that was quick :-) I fell for the enter != linebreak trap again. Works like a charm with Visual Studio 2017 now, thanks a bunch!
  • That looks like a bad (read: inefficient and inflexible) C++20 / GSL span... aside from allowing non-contiguous sequences.
  • Now you mention the c++ guys call it span, I found it. They should have named it slice it I could have saved myself the work. But... @Deduplicator ... what is inefficient about this implementation?
  • You have three members: Reference to container, start of slice, length of slice. But for a random-access-container, you only need begin-terator and length or end-Iterator. Also, you should use noexcept and constexpr.
  • But my container is random access (read only of course). And also, at first glance I think the std::span is also a matter of taste... they need the subspan function while my slice can pose as an array replacement for sub-functions. And it works both for array and for slice sources. And I also don't "go pointer" in my implementation. And last not least - with 1 extra function I could retrieve the source. That is one thing iterators usually do not offer AFAIK.
  • You know, ignorance of the container, aside from just enough to find all the elements in the sequence, is a feature and not a bug. It greatly increases flexibility at no extra cost.