Val
Val

Reputation: 209

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

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?

Upvotes: 5

Views: 21217

Answers (3)

Alex
Alex

Reputation: 7838

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.

Upvotes: 5

Dan
Dan

Reputation: 13160

In C++ land, instead of using ranges, iterators are used. An iterator is an index into the container that points to a certain element. So to get an iterator to the beginning, you use vec.begin(), and to get an iterator to n you use vec.begin() + n. If you want to iterate over this, you can simply do

for (atd::vector<Foo>::iterator it = vec.begin(); it != vec.begin() + n; ++it)

If you want to make a new vector, you can use the constructor that Luchian mentions like so:

std::vector<Foo> vec2(vec.begin(), vec.begin() + n)

Upvotes: 3

Luchian Grigore
Luchian Grigore

Reputation: 258568

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.

Upvotes: 8

Related Questions