Erase an element from a vector by index in C++
This post will discuss how to erase an element from a vector by its index in C++.
The standard solution to remove an element from the vector is using the std::vector::erase member function. To remove an element from a vector by its index, we can use pointer arithmetic, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> #include <vector> #include <algorithm> #include <iterator> template <typename T> void remove(std::vector<T>& v, size_t index) { v.erase(v.begin() + index); } int main() { std::vector<int> v = {1, 2, 3, 4, 5}; int index = 2; remove(v, index); std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); return 0; } |
Output:
1 2 4 5
Alternatively, we can use the std::advance standard algorithm to advance the iterator by specified positions to point to the desired index.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> #include <vector> #include <algorithm> #include <iterator> template <typename T> void remove(std::vector<T> &v, size_t index) { auto it = v.begin(); std::advance(it, index); v.erase(it); } int main() { std::vector<int> v = {1, 2, 3, 4, 5}; int index = 2; remove(v, index); std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); return 0; } |
Output:
1 2 4 5
That’s all about erasing an element from a vector by index 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 :)