forward_list::unique( ) in C++ STL

C++Server Side ProgrammingProgramming

Given is the task to show the working of forward_list::unique( ) function in C++.

Forward list are sequence containers that allow constant time insert and erase operations anywhere within the sequence. Forward list are implement as a singly-linked lists. The ordering is kept by the association to each element of a link to the next element in the sequence.

forward_list::unique( ) is a function in c++ standard library function which is used to remove the all duplicate elements from forward list. Notice that an element is only removed from the forward_list container if it compare equal to the element immediately it. Thus, this function is especially useful for sorted lists.

Syntax

Forwardlist_name.unique(binarypredicate name)

Syntax for binary predicate

bool name(data type a, data type b)

Parameter − This function accepts a single parameter which is a binary predicate that returns true if the elements should be treated as equal.

Example

Output – List : 4, 4, 17, 32, 45, 56, 56, 45, 32, 4, 17, 17
   After Unique operation output is
      Unique list : 4, 17, 32, 45, 56
Output – List : 15.2, 74.0, 3.14, 15.2, 69.5, 74.0, 3.14, 18.5, 3.99
   After Unique operation output is
      Unique list : 3.14, 3.99, 15.2, 18.5, 69.5, 74.0

Approach can be followed

  • First we create binary predicate function.

  • Then we initialize the forward list.

  • Then we defines the unique( ) function.

  • Then we print the forward list after unique operation.

By using above approach we can remove the duplicate element from the forward list.

Example

// C++ code to demonstrate the working of forward_list::unique( )
#include<iostream.h>
#include<forward_list.h>
Using namespace std;
// function for binary predicate
bool cmp(int a, int b){
   return (abs(a) == abs(b))
}
int main(){
   // initializing the forward list
   forward_list<int> List = { 2, 4, 6, 3, 5, 3, 4, 4, 9, 1, 6, 6, 2, 2, 9 }
   cout<< " Elements of List:";
   for( auto x = List.start(); x != List.end(); ++x )
      cout<< *x << " ";
   // defining of function that performs the Unique operation
   List.unique();
   cout<< “ Unique List :”;
   for(auto x = List.start(); x != List.end(); ++x)
      cout<< *x << " ";
   return 0;
}

Output

If we run the above code then it will generate the following output

OUTPUT – List : 2, 4, 6, 3, 5, 4, 4, 9, 1, 6, 6, 2, 2, 9
   Unique List : 1, 2, 3, 4, 5, 6, 9
OUTPUT – List : 15.2, 74.0, 3.14, 15.2, 69.5, 74.0, 3.14, 18.5, 3.99
   Unique List : 3.14, 3.99, 15.2, 18.5, 69.5, 74.0
raja
Published on 28-Feb-2020 11:02:21
Advertisements