Answer the question
In order to leave comments, you need to log in
How to slice an array?
how to make a slice which in python is drawn like this:
d = d[2:]
Answer the question
In order to leave comments, you need to log in
I advise you to dig in the direction std::span
. It needs begin and end iterators, like v.begin()
and v.begin() + 2
. This way you can create a slice without copying all the elements of the array.
In C++ there is no concept of "arbitrary array", and this gets in the way.
But it is not difficult to write this most arbitrary array (without storage)
template <class T>
struct Buf1d {
size_t size;
T* d;
constexpr Buf1d() : size(0), d(nullptr) {}
constexpr Buf1d(size_t aSize, T* aD) : size(aSize), d(aD) {}
Buf1d(std::vector<T>& x) : size(x.size()), d(x.data()) {}
}
template <class T>
Buf1d<T> Buf1d<T>::sliceLeft(size_t x) const
{
if (x >= size) {
return {};
} else {
return { size - x, d + x };
}
}
template<class T>
std::vector<T> sliceLeft(const std::vector<T>& v, size_t x)
{
if (x >= v.size()) {
return {};
} else {
std::vector<T> r;
r.insert(r.end(); v.begin() + x, v.end());
return r;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question