Array slicing involves taking a subset from an array and allocating a new array with those elements.
In C++ you can create a new vector of the elements in myVector, from startIndex to endIndex (exclusive), like this:
Careful: there's a hidden time and space cost here! It's tempting to think of slicing as just "getting elements," but in reality you are:
- allocating a new vector
- copying the elements from the original vector to the new vector
This takes time and space, where n is the number of elements in the resulting vector.
That's a bit easier to see when you save the result of the slice to a variable:
But a bit harder to see when you don't save the result of the slice to a variable:
So keep an eye out. Slice wisely.
Interview Cake