C++ Standard Library C++ STL Library

C++ <algorithm> - remove() Function



The C++ algorithm::remove function is used to remove the specified value val in the range [first, last). This transforms the range [first, last) into range containing no element equal to the value val and returns iterator to the new end of the range. Please note that, the function cannot alter the size of the container. The removal is done by swapping the element with the next element which is not equal to val.

Syntax

template <class ForwardIterator, class T>
  ForwardIterator remove (ForwardIterator first, 
                          ForwardIterator last, 
                          const T& val);

Parameters

first Specify initial position of the forward iterator. The range used is [first,last).
last Specify final position of the forward iterator. The range used is [first,last).
val Specify the value to be removed.

Return Value

Returns an iterator to the element that follows the last element not removed.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the algorithm::remove function is used to remove the specified value from the given vector.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std; 

int main (){
  vector<int> vec{10, 20, 30, 10, 10, 20, 50};
  vector<int>::iterator it;

  cout<<"Before remove call, vec contains:";
  for(it = vec.begin(); it != vec.end(); ++it)
    cout<<" "<<*it;

  //remove all occurrences of 10
  auto newend = remove(vec.begin(), vec.end(), 10);

  cout<<"\nAfter remove call, vec contains:";
  for(it = vec.begin(); it != newend; ++it)
    cout<<" "<<*it;

  return 0;
}

The output of the above code will be:

Before remove call, vec contains: 10 20 30 10 10 20 50
After remove call, vec contains: 20 30 20 50

❮ C++ <algorithm> Library