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.
std::forward_list
This lesson provides an in-depth exploration of std::forward_list
, covering creation, management, and advanced list operations