List Unique Function

C++ List unique

C++ List unique function removes all the duplicate elements present consecutively from the list.

Syntax

Example

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

Parameter

pred : It is a binary predicate that takes two values of same type. It returns true, if both the values are equal otherwise false.

Syntax of the predicate function would be:

Example

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

Return value

It does not return any value.

Example 1

Let's see a simple example

Example

#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:

Example 2

Let's see a simple example when predicate function is passed to the parameter.

Example

#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:

Output

12 ,13.1,14.7,15.5

Input Required

This code uses input(). Please provide values below: