Extract a subvector from a vector in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8}; int start = 2; int end = 4; std::vector<int> slice(v.begin() + start, v.begin() + end + 1); for (int &i: slice) { std::cout << i << ' '; } return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8}; int start = 2; int end = 4; std::vector<int> slice; slice.insert(slice.begin(), v.begin() + start, v.begin() + end + 1); for (int &i: slice) { std::cout << i << ' '; } return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8}; int start = 2; int end = 4; std::vector<int> slice; std::copy(v.begin() + start, v.begin() + end + 1, std::back_inserter(slice)); for (int &i: slice) { std::cout << i << ' '; } return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8}; int start = 2; int end = 4; std::vector<int> slice; slice.assign(v.begin() + start, v.begin() + end + 1); for (int &i: slice) { std::cout << i << ' '; } return 0; } |
Output:
2 3 4
That’s all about extracting a subvector from a vector in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)