list unique() in C++ STL

list::unique() is an inbulit function in C++ STL which removes all duplicate consecutive elements from the 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate the
// unique() function
#include <bits/stdc++.h>
using namespace std;
  
// Function for binary_predicate
bool compare(double a, double b)
{
    return ((int)a == (int)b);
}
  
// Driver code
int main()
{
    list<double> list = { 2.55, 3.15, 4.16, 4.16,
                          4.77, 12.65, 12.65, 13.59 };
  
    cout << "List is: ";
  
    // unique operation on list with no parameters
    list.unique();
  
    // starts from the first element
    // of the list to the last
    for (auto it = list.begin(); it != list.end(); ++it)
        cout << *it << " ";
  
    // unique operation on list with parameter
    list.unique(compare);
  
    cout << "\nList is: ";
  
    // starts from the first element
    // of the list to the last
    for (auto it = list.begin(); it != list.end(); ++it)
        cout << *it << " ";
  
    return 0;
}

chevron_right


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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


3


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.