Removing Consecutive Duplicates in std::forward_list

How can I remove consecutive duplicate elements from a forward_list?

The unique() member function in std::forward_list removes consecutive duplicate elements from the list. It operates on sorted lists, so it's often used in conjunction with sort().

#include <forward_list>
#include <iostream>

int main() {
  std::forward_list<int> list{
    1, 2, 2, 3, 3, 3, 4, 4, 5};

  list.sort();    
  list.unique();  

  for (int i : list) {
    std::cout << i << ' ';
  }
}
1 2 3 4 5

By default, unique() uses operator== to compare elements. You can also pass a custom predicate:

#include <forward_list>
#include <iostream>

bool areConsecutive(int first, int second) {
  return second == first + 1; }

int main() {
  std::forward_list<int> list{
    1, 2, 3, 5, 6, 7, 9};

  list.unique(areConsecutive);  

  for (int i : list) {
    std::cout << i << ' ';
  }
}
1 3 5 7 9

Here, only consecutive elements that satisfy the areConsecutive predicate are removed.

Linked Lists using std::forward_list

This lesson provides an in-depth exploration of std::forward_list, covering creation, management, and advanced list operations

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Iterator Invalidation in std::forward_list
When do iterators become invalidated in a std::forward_list?
Using splice_after() in std::forward_list
How can I transfer elements from one forward_list to another using splice_after()?
Merging Sorted Lists in std::forward_list
How can I merge two sorted forward_list objects into one sorted list?
Using Lambda Expressions with remove_if() in std::forward_list
How can I use a lambda expression as the predicate for remove_if() in a forward_list?
Reversing Elements in std::forward_list
How can I reverse the order of elements in a forward_list?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant