Forward lists are sequential structures that permit rapid insertion and deletion operations at any point within the sequence. They are constructed as singly linked lists, where each element is linked to the subsequent element in the sequence to preserve the order.
The forwardlist::unique function in the C++ standard library serves the purpose of removing all redundant elements from a forward list. It's important to highlight that an element will only be removed from the forwardlist if it matches the element directly preceding it. Consequently, this technique proves to be particularly beneficial for sorted lists.
Syntax:
It has the following syntax:
forwardlist.unique(binarypredicate name)
Syntax for the binary predicate:
bool name(data type a, data type b)
This function accepts a solitary parameter, which is a binary predicate that evaluates to true when the items are deemed equivalent.
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
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 primary limitation of using list and forwardlist compared to other sequence containers is the absence of direct element access by location, like the operator . In order to reach a specific element in a forwardlist, it is necessary to iterate from a known location (e.g., the beginning or end of the list) to the desired element, which entails a linear time complexity.
Example:
Let's consider an example to demonstrate the functionality of the forwardlistunique method in C++.
// 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:
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