Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a range of items from vector in C++

Tags:

c++

slice

vector

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?

like image 248
Val Avatar asked Dec 07 '22 11:12

Val


2 Answers

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.

like image 104
Luchian Grigore Avatar answered Dec 09 '22 14:12

Luchian Grigore


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.

like image 31
Alex Avatar answered Dec 09 '22 13:12

Alex