std::erase
The std::erase function is used to remove elements from the container giving the iterator its position. It can also remove the range of elements when the iterator to starting position and ending position are provided.
Syntax of std::erase
container.erase(position); // to eliminate single element or container.erase(starting_position, ending_position); // to eliminate a range of elements
Here,
- position: It is the iterator to the element to be removed.
- starting_position: iterator to the starting point of the range to be eliminated.
- ending_position: It is the iterator to the ending point of the range to be eliminated.
Erase-Remove Idiom in C++
Erase-Remove-Idiom is a C++ STL (Standard Template Library) technique to remove elements from a container. It is used to remove all the elements satisfying certain conditions from the container.
The erase-remove idiom is especially useful in array-based containers like vectors, where each elimination requires all the remaining elements to adjust. In the worst case, this may lead to O ( n2 ) time complexity. This technique avoids this by providing the elimination of the elements in a single parse. That is why, the erase-remove idiom provides O( n ) time complexity.
In this technique, we use the combination of two member functions of the container to remove the elements efficiently.
- std::erase
- std::remove or std::remove_if
It is due to the use of this function that this technique is called the erase-remove idiom.