![]() |
VOOZH | about |
In C++, vector erase() is a built-in function that is used to delete elements from the vector. It removes an element of a specific position or range of elements from the vector.
1 2 4 5
In the above example, erase() method remove the element(3) which is present at index 2.
Vector erase method has two implementations:
// Remove single element
v.erase(pos);// Erase range of elements
v.erase(first, last);
where,
Parameters:
Return Value:
The following programs illustrates how to use the vector erase() method to remove elements in different cases:
Example: Remove an Element Using Index from a Vector
1 3 4 5
Explanation: The iterator of the element at index 1 is determined by adding the index to vector begin() iterator. Then vector erase() is used to remove it.
Example: Remove the Last Element from the Vector
1 2 3 4
In the above program, we use end() iterator to delete the last element of the vector, which is 5.
Example: Remove a Range of Elements from a Vector
1 5
Explanation: The iterator to the part of the vector to be removed is passed to the vector erase() method. It removed that part from the array.
In a vector, both vector clear() and vector erase() are used for element removal, but they serve different purposes. Following are the cases which describe when to use clear() and when to use erase():