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 1After 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