Get a slice or a sub-vector from a vector in C++
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#include <iostream> #include <vector> template<typename T> void print(std::vector<T> const &v) { for (auto i: v) { std::cout << i << ' '; } std::cout << std::endl; } template<typename T> std::vector<T> slice(std::vector<T> const &v, int m, int n) { auto first = v.cbegin() + m; auto last = v.cbegin() + n + 1; std::vector<T> vec(first, last); return vec; } int main() { // input vector std::vector<int> v = { 1, 2, 3, 4, 2, 2, 4, 6, 5 }; // starting and ending index int m = 4, n = 7; std::vector<int> sub_vec = slice(v, m, n); print(sub_vec); return 0; } |
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:
1 2 3 4 5 6 7 |
template<typename T> std::vector<T> slice(std::vector<T> &v, int m, int n) { std::vector<T> vec(n - m + 1); std::copy(v.begin() + m, v.begin() + n + 1, vec.begin()); return vec; } |
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:
1 2 3 4 5 6 7 |
template<typename T> std::vector<T> slice(std::vector<T> &v, int m, int n) { std::vector<T> vec; std::copy(v.begin() + m, v.begin() + n + 1, std::back_inserter(vec)); return vec; } |
That’s all about getting a slice or a sub-vector 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 :)