forward_list::unique() in C++ STL

forward_list::unique() is an inbuilt function in C++ STL which removes all consecutive duplicate elements from the forward_list. It uses binary predicate for comparison.

Syntax:

forwardlist_name.unique(BinaryPredicate name)

Parameters: The function accepts a single 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 a)

Return value: The function does not return anything.

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(int a, int b)
{
    return (abs(a) == abs(b));
}
// This function can also be used and passed inside
// unique(), to get the same result
*/
  
int main()
{
  
    forward_list<int> list = { 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 2, 4, 4 };
  
    cout << "List of elements before unique operation is: ";
  
    // 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 forward list
    list.unique();
    cout << "\nList of elements after unique operation 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 of elements before unique operation is: 1 1 1 1 2 2 2 2 3 3 3 2 4 4 
List of elements after unique operation is: 1 2 3 2 4


My Personal Notes arrow_drop_up

Contented with little yet wishing for more

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.



Improved By : babaurbeautiful



Article Tags :
Practice Tags :


1


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