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:

Download  Run Code

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.

Download  Run Code

Output:

1 2 4 5

That’s all about erasing an element from a vector by index in C++.