I need to get a range of elements from std::vector
. Similar to the python slice operator:
range = vector[0:n]
The obvious way is to iterate through the required elements. Is there any other better way?
One of vector's constructors is:
template <class InputIterator>
vector ( InputIterator first, InputIterator last, const Allocator& = Allocator() );
So you need only create a new vector passing the required iterators.
vector<T>
has a constructor that takes two iterators that identify a range.
Example:
std::vector<int> range( &v[0], &v[0]+n );
Note that this would work even if v
is a regular array and not a vector
because a pointer to an element in an array behaves like an iterator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With