This post will discuss how to extract a subvector from a vector in C++.

1. Using range constructor

The range constructor creates a new vector containing all elements from the specified range. To extract a subvector from a vector, pass the iterators to the starting and the ending positions of the subvector. This is demonstrated below:

Download  Run Code

Output:

2 3 4

2. Using std::vector::insert

For an existing vector, we can use the std::vector::insert member function that takes an iterator to the destination vector and iterators specifying the range of the vector elements. A typical invocation for this function would look like:

Download  Run Code

Output:

2 3 4

3. Using std::copy

Another option is to use the std::copy standard algorithm to copy all elements of the specified range to another vector. Here’s how the code would look like:

Download  Run Code

Output:

2 3 4

4. Using std::vector::assign

Finally, we can use the std::vector::assign member function to replace the vector contents with elements in the specified range. The following C++ program demonstrates it:

Download  Run Code

Output:

2 3 4

That’s all about extracting a subvector from a vector in C++.