How to Remove Element from Vector in C++: Syntax and Examples
std::vector in C++, use the erase() method with an iterator pointing to the element. For removing by value, combine std::remove() with erase() to delete all matching elements efficiently.Syntax
The erase() method removes elements from a vector by position or range. The std::remove() algorithm shifts elements to remove by value but does not change vector size, so it must be combined with erase() to actually delete elements.
vec.erase(position);removes element atposition.vec.erase(start, end);removes elements in the range[start, end).vec.erase(std::remove(vec.begin(), vec.end(), value), vec.end());removes all elements equal tovalue.
vec.erase(position); // Remove element at iterator position vec.erase(start, end); // Remove elements in range [start, end) vec.erase(std::remove(vec.begin(), vec.end(), value), vec.end()); // Remove all elements equal to value
Example
This example shows how to remove a single element by index and how to remove all elements with a specific value from a vector.
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> numbers = {10, 20, 30, 20, 40, 20, 50}; // Remove element at index 2 (value 30) numbers.erase(numbers.begin() + 2); // Remove all elements with value 20 numbers.erase(std::remove(numbers.begin(), numbers.end(), 20), numbers.end()); // Print remaining elements for (int num : numbers) { std::cout << num << " "; } std::cout << std::endl; return 0; }
Common Pitfalls
One common mistake is using std::remove() alone, which only moves elements but does not reduce the vector size, leaving unwanted elements at the end. Another is erasing elements inside a loop without updating iterators, which can cause invalid access or skip elements.
Always combine std::remove() with erase() to actually remove elements by value. When erasing in loops, update the iterator properly.
#include <vector> #include <algorithm> // Wrong: std::remove alone does not shrink vector size std::vector<int> v = {1, 2, 3, 2, 4}; std::remove(v.begin(), v.end(), 2); // Elements moved but size unchanged // Correct: combine remove and erase v.erase(std::remove(v.begin(), v.end(), 2), v.end());
Quick Reference
| Operation | Code Example | Description |
|---|---|---|
| Remove by position | vec.erase(vec.begin() + index); | Removes element at given index. |
| Remove by range | vec.erase(vec.begin() + start, vec.begin() + end); | Removes elements in [start, end) range. |
| Remove by value | vec.erase(std::remove(vec.begin(), vec.end(), value), vec.end()); | Removes all elements equal to value. |
| Clear all | vec.clear(); | Removes all elements from vector. |
Key Takeaways
erase() with iterators to remove elements by position or range.std::remove() with erase() to remove elements by value correctly.std::remove() alone as it does not change vector size.clear() to remove all elements from a vector quickly.