C++ Standard Library C++ STL Library

C++ <list> - remove() Function



The C++ list::remove function is used to delete all occurrences of specified element from the list container.

Syntax

void remove (const value_type& val);
void remove (const value_type& val);

Parameters

val Specify the value of the element which need to be removed from the list.

Return Value

None.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the list::remove function is used to delete all occurrences of specified element from the list called MyList.

#include <iostream>
#include <list>
using namespace std;
 
int main (){
  list<int> MyList{10, 20, 30, 40, 50, 30, 30, 40};
  list<int>::iterator it;

  cout<<"MyList contains: ";
  for(it = MyList.begin(); it != MyList.end(); it++)
    cout<<*it<<" ";

  //Remove all occurrences of 30 from the list
  MyList.remove(30);
  
  cout<<"\nMyList contains: ";
  for(it = MyList.begin(); it != MyList.end(); it++)
    cout<<*it<<" ";

  return 0;
}

The output of the above code will be:

MyList contains: 10 20 30 40 50 30 30 40 
MyList contains: 10 20 40 50 40 

❮ C++ <list> Library