C++ Vector Erase: Usage & Examples
In C++, the erase function of a vector is used to delete one or a series of elements from the vector. It has two different usages:
- Remove the element at the specified position using the iterator, and return an iterator pointing to the position after the deleted element. For example:
- vector
myVector = {1, 2, 3, 4, 5};
auto it = myVector.erase(myVector.begin() + 2);
// Erase the element at position 2, which is 3, and return an iterator pointing to 4
// myVector becomes {1, 2, 4, 5} - Delete elements within the range [first, last) and return an iterator pointing to the position after the deleted elements. For example:
- myVector vector
= {1, 2, 3, 4, 5};
auto it = myVector.erase(myVector.begin() + 1, myVector.begin() + 4);
// Erase elements at positions 1, 2, and 3, which are 2, 3, 4, return an iterator pointing to 5
// myVector becomes {1, 5}
Note: After deleting elements using the erase function, all elements following the deleted element will automatically be shifted forward, so iterators may become invalidated and require careful handling.