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?
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);
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);