-1

I want to represent elements i through i+k-1 of an std::array as another std::array, for constexpr i and k - preferably with no copying and in a constexpr function.

Can this be done? If so, what's the right way to approach this?

einpoklum
  • 118,144
  • 57
  • 340
  • 684

2 Answers2

2

Copying is inevitable with std::array. You can avoid copying if you can use span<T, N> from the Microsoft Guideline Support Library.

If you have to stick with std::array then you can introduce this helper function:

template<std::size_t OFFSET, std::size_t K, class T, std::size_t N>
std::array<T, K>
subarray(const std::array<T, N>& a)
{
    static_assert(OFFSET+K<=N, "your error message here");

    std::array<T, K> s;
    std::copy(a.begin()+OFFSET, a.begin()+OFFSET+K, s.begin());
    return s;
};

Use it like this:

std::array<int, 5> a = { 1, 2, 3, 4, 5 };
std::array<int, 3> s = subarray<1, 3>(a);
Leon
  • 31,443
  • 4
  • 72
  • 97
2

What you are asking is for a slice of an array or may be even a vector. Sadly, We do not have anything in the standard library (until C++17), but as Leon has mentioned in his answer, you can use span for that.

GSL implementation: https://github.com/Microsoft/GSL/blob/master/include/span.h

std::array<int, 4> arr = {1, 2, 3, 4};
span<int> s{&arr[0], 2};

My implementation of slice(test) : https://github.com/arun11299/Slices-in-Cpp\

std::vector<int> vec{1,2,3,4,5,6,7,8,9,10};

// all elements
auto vslice = make_slice(vec, 0, vec.size());
assert(len(vslice) == 10);

vslice = vslice(beg, 8);

assert(len(vslice) == 8);
Arunmu
  • 6,837
  • 1
  • 24
  • 46
  • 2
    How can you be so certain you must have an array here? If that's the case, I'm inclined to think there is an XY problem here. If you can describe the unusual circumstances that make you think you need this, maybe we can come up with a solution that can actually work. – R. Martinho Fernandes Jun 12 '16 at 21:06
  • @einpoklum I am confused after reading this "Spans are great, I know about spans, it's just what I'm after here". Then why not use `span` ? – Arunmu Jun 13 '16 at 05:53
  • @Arunmu: Was missing a "not": A span does not work for me - I need a proper `std::array`. Ok, "need" is a strong work, let's say I would "really much rather have" an std::array. Spans are great, I know about spans, it's just _not_ what I'm after here. – einpoklum Jun 13 '16 at 06:55
  • @einpoklum Hmm..seems you are pretty strict on having on an `array` container. Basing on the assumption that what you are holding in an array is costly to copy, how about creating an array of `reference_wrapper` (I know it's a cheap shot) – Arunmu Jun 13 '16 at 07:21