Linked Lists using std::forward_list

Removing Consecutive Duplicates in std::forward_list

How can I remove consecutive duplicate elements from a forward_list?

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved