C++ List unique
The unique function in C++ eliminates all consecutive duplicate elements from a list, ensuring only unique elements remain.
Syntax
void unique();
void unique(BinaryPredicate pred);
Parameter
pred : A binary predicate is a function that accepts two values of the same type and evaluates to true if both values are identical, otherwise it returns false.
Syntax of the predicate function would be:
bool pred( type1 &x, type2 &y);
Return value
It does not return any value.
Example 1
Let's see a simple 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 examine a basic scenario where a predicate function is supplied as an argument.
#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