Let's look at a picture. You have a singly-linked list with five elements.
1 --> 2 --> 3 --> 4 --> 5 --> null
^ ^
| |
begin end
Now you want to make the beginning of the list point to the node with 4
.
1 --> 2 --> 3 --> 4 --> 5 --> null
^ ^
| |
begin end
Notice how in this picture, there is no longer anything pointing to the node with 1
. Even if you adjusted the end
iterator, there would be no way to follow the arrows to get to 1
. Nodes 1
, 2
, and 3
are left dangling, never to be found again. This is one reason why std::forward_list
will not let you do this.
There is simply no path from 5
to 1
unless you make one. You could make one, though. One approach requires calculating an iterator pointing to the node with 5
and one pointing to the node with 4
.
auto slice_begin = list.before_begin(); // For consistent naming
auto slice_end = std::next(list.begin(), 3); // Calculate iterator to 4
auto destination = std::next(slice_end); // Calculate iterator to 5
This gives you the following picture.
1 --> 2 --> 3 --> 4 --> 5 --> null
^ ^ ^
| | |
slice_begin slice_end |
|
destination
Now the goal is to move the nodes strictly between slice_begin
and slice_end
so that they come after destination
. Fortunately, forward_list
has a method for doing this.
list.splice_after(destination, list, slice_begin, slice_end);
Now you have your desired 4 -> 5 -> 1 -> 2 -> 3
.