Linked Lists using std::forward_list

Reversing Elements in std::forward_list

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

Abstract art representing computer programming

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.

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