Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


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

Syntax

void unique();

template <class BinaryPredicate>
  void unique (BinaryPredicate binary_pred);
void unique();

template <class BinaryPredicate>
  void unique (BinaryPredicate binary_pred);

Parameters

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

Return Value

None.

Time Complexity

Linear i.e, Θ(n).

Example:

In the below example, the list::unique 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
  cout<<"\n\nRemove all occurrences of 30 from the MyList.\n";
  MyList.unique(30);
  
  cout<<"Now, MyList 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 

Remove all occurrences of 30 from the MyList.
Now, MyList contains: 10 20 40 50 40  

❮ C++ - List