F
F
fronttrty2020-06-18 18:35:52
C++ / C#
fronttrty, 2020-06-18 18:35:52

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

2 answer(s)
A
Anton Zhilin, 2020-06-18
@Anton3

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.

M
Mercury13, 2020-06-18
@Mercury13

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()) {}
}

And this Buf1d can come up with other functions, for example:
template <class T>
Buf1d<T> Buf1d<T>::sliceLeft(size_t x) const
{
  if (x >= size) {
    return {};
  } else {
    return { size - x, d + x };
  }
}

If you need storage, then, for example, you can use the good old vector.
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 question

Ask a Question

731 491 924 answers to any question