Remove a range of elements from a vector in C++
In this post, we’ll see how to remove the range of elements from a vector between specified indices in C++.
We can use the public member function std::vector::erase of the container std::vector for removing a part of the vector between the specified indices.
We have two overloaded versions of the erase() function: the first one removes only a single element at the specified position, and the second one removes all elements between the specified range. The solution is feasible using either one of them:
1. Using erase(const_iterator pos) function
|
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 |
#include <iostream> #include <vector> #include <iterator> template<typename T> void slice(std::vector<T> &v, int m, int n) { int k = n - m + 1; auto it = v.cbegin() + m; while (it != v.cend() && k--) { it = v.erase(it); } } int main() { std::vector<int> v = { 1, 2, 3, 4, 9, 8, 7, 6, 5 }; int m = 4, n = 7; slice(v, m, n); for (int const &i: v) { std::cout << i << ' '; } return 0; } |
Output:
1 2 3 4 5
2. Using erase(const_iterator first, const_iterator last) function
|
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 |
#include <iostream> #include <vector> #include <iterator> template<typename T> void slice(std::vector<T> &v, int m, int n) { auto first = v.cbegin() + m; auto last = v.cbegin() + n + 1; v.erase(first, last); } int main() { std::vector<int> v = { 1, 2, 3, 4, 9, 8, 7, 6, 5 }; int m = 4, n = 7; slice(v, m, n); for (int const &i: v) { std::cout << i << ' '; } return 0; } |
Output:
1 2 3 4 5
That’s all about removing a range of elements 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 :)