Reversing Elements in std::forward_list

How can I reverse the order of elements in a forward_list?

The reverse() member function in std::forward_list reverses the order of the elements in the list.

#include <forward_list>
#include <iostream>

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

  list.reverse();  

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

After calling reverse(), the order of the elements is reversed.

Note that reversing a forward_list is a linear time operation, as it needs to traverse the entire list to reverse the links between the nodes.

Also, since forward_list is a singly-linked list, there's no rbegin() or rend() for reverse iteration. If you need to frequently access the elements in reverse order, you might consider using a different container like list (doubly-linked list) or deque (double-ended queue), which provide bidirectional iterators.

#include <forward_list>
#include <iostream>

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

  for (
    auto it = list.rbegin();
    it != list.rend();
    ++it
  ) {
    std::cout << *it << ' ';
  }
}
error: 'rbegin': is not a member of 'std::forward_list'
error: 'rend': is not a member of 'std::forward_list'

However, if you only need to reverse the elements once, reverse() is a convenient and efficient method.

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()?
Removing Consecutive Duplicates in std::forward_list
How can I remove consecutive duplicate elements from a forward_list?
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?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant