list unique() in C++ STL
Last Updated :
13 Jun, 2022
list::unique() is an inbuilt function in C++ STL which removes all duplicate consecutive elements from the list. It works only on sorted list.
Syntax:
list_name.unique(BinaryPredicate name)
Parameters: The function accepts a single and optional parameter which is a binary predicate that returns true if the elements should be treated as equal. It has following syntax:
bool name(data_type a, data_type b);
Return value: This function does not return anything.
Below is the implementation of above function:
CPP
#include <bits/stdc++.h>
using namespace std;
bool compare( double a, double b)
{
return (( int )a == ( int )b);
}
int main()
{
list< double > list = { 2.55, 3.15, 4.16, 4.16,
4.77, 12.65, 12.65, 13.59 };
cout << "List is: " ;
list.sort();
list.unique();
for ( auto it = list.begin(); it != list.end(); ++it)
cout << *it << " " ;
list.unique(compare);
cout << "\nList is: " ;
for ( auto it = list.begin(); it != list.end(); ++it)
cout << *it << " " ;
return 0;
}
|
Output
List is: 2.55 3.15 4.16 4.77 12.65 13.59
List is: 2.55 3.15 4.16 12.65 13.59
Time Complexity – O(nlogn) due to sorting of list
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...