English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ List unique() usage and example

C++ List (List)

C ++The unique() function of the list removes duplicate elements from the list.

Syntax

void unique();
void unique(BinaryPredicate pred);

Parameter

predThe unique() function of the list removes all duplicate elements from the linked list. If pred is specified, pred is used to determine whether to delete.

The syntax of the pred function is:

bool pred(type1 &x, type2 &y);

Return value

It does not return any value.

Instance1

Let's look at a simple instance

#include iostream>
#include<list>
using namespace std;
int main()
{
 list<char> l1={'j','a','a','v','v','a'};
 list<char> ::iterator itr;
 l1.unique();
  for(itr=l1.begin();itr!=l1.end();++itr)
  std::cout << *itr << " ";
    return 0;
}

Output:

java

Instance2

Let's look at a simple example, passing the pred function to the parameter.

#include iostream>
#include<list>
using namespace std;
bool pred(float x,float y)
{
    return(int(x)==int(y));
}
int main()
{
 list<float> l1={12,12.5,12.4,13.1,13.5,14.7,15.5};
 list<float> ::iterator itr;
 l1.unique(pred);
 for(itr=l1.begin();itr!=l1.end();++itr)
 std::cout << *itr << ", ";
 return 0;
}

Output:

12 ,13.1,14.7,15.5

C++ List (List)