Forward Listunique In C++

Forward lists are sequence structures that allow constant-time insert and erase processes anywhere in the sequence. Forward lists are implemented as singly linked lists. The ordering is maintained by associating each element with a link to the next element in the sequence.

forwardlist::unique is a function in the C++ standard library that is used to eliminate all duplicate entries from a forward list. It should be noted that an element is only deleted from the forwardlist container if it compares to the element immediately before it. As a result, this method is especially helpful for sorted lists.

Syntax:

It has the following syntax:

Example

forwardlist.unique(binarypredicate name)

Syntax for the binary predicate:

Example

bool name(data type a, data type b)

This function takes a single parameter, it is a binary predicate that returns true if the items should be considered as equal.

Example

List : 4,5,6,4,8,8,5
Unique list : 4,5,6,8
List: 5.3,5.4,8,9,5.3,5.4
Unique list :5.3,5.4,8,9

Approach

Example

We begin with creating a binary predicate function.
The forward list is then initialized.
The unique() function is then defined.
Following the unique operation, output the forward list.

The fundamental drawback of utilizing list and forwardlist over other sequence containers is that they do not provide direct access to any element by its location, such as using the operator . To access any of the elements in a forwardlist, iteration must be performed from a known point (such as the starting point or end of the list) to the element's position, requiring linear time.

Example:

Let's take an example to illustrate the use of forwardlistunique function in C++.

Example

// C++ program to illustrate the 
// unique() function 
#include <bits/stdc++.h> 
using namespace std; 
// binary_predicate method /*bool compare(int a, int b) return (abs(a) == abs(b)); 
// To get the same effect, this method may be utilized and provided within // unique().
int main() 
{ 

	
	forward_list<int> lists = {1,1,4,4,4,2,2,2,2,5,5,5,5,5}; 

	cout << "The elements of the list before the unique operation: "; 

	// iterating over the list
	for (auto ite = lists.begin(); ite != lists.end(); ++ite) 
		cout << *ite<< " "; 

	// the unique operation 
	lists.unique(); 
	cout << "\nElements after the unique operation is: "; 

	// display of each element
	for (auto ite = lists.begin(); ite != lists.end(); ++ite) 
		cout << *ite << " "; 

	return 0; 
}

Output:

Output

The elements of the list before the unique operation: 1 1 4 4 4 2 2 2 2 5 5 5 5 5 
Elements after the unique operation is: 1 4 2 5

Input Required

This code uses input(). Please provide values below: