In this quick article, we’ll explore to get a slice or a sub-vector from a given vector in C++.

1. Using Range Constructor

The idea is to get input iterators to the starting and ending position in the vector and pass them to the range constructor of the vector class to get a sub-vector.

Download  Run Code

Output:

2 2 4 6

2. Using std::copy function

We can also use the standard algorithm std::copy for copying part of a vector to another vector, as shown below:

Download  Run Code

 
Before calling std::copy, make sure the destination vector has enough space to accommodate all elements. If this is not the case, prefer using std::back_insert iterator, which will call push_back() on the specified vector, as shown below:

Download  Run Code

That’s all about getting a slice or a sub-vector from a vector in C++.