How does splice works? I read about it in http://www.cplusplus.com/reference/list/list/splice/
I couldn't understand this part from the code in the above link:
mylist1.splice ( mylist1.begin(), mylist1, it, mylist1.end());
The C++ function std::list::splice() transfers the elements in the range of first to last from x to *this by using move semantics. The elements are inserted before the element pointed to by position.
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice() .
Imagine you have a list of integers with the following contents:
[1, 2, 3, 4, 5]
Now you create an iterator in the list called it
and you advance it of 3 positions:
[1, 2, 3, 4, 5]
^
'it' points here
then you splice the list into itself, to the list's beginning (first parameter), in the same list (second parameter), from the position pointed by it
(third parameter), to the end (fourth parameter), which gives the following result:
[4, 5, 1, 2, 3]
So you effectively rotated the list of two elements to the right.
The reason you need to supply the source list
is that otherwise the elements can't be removed from it.
The fourth parameter of the splice function moves (not copy) your range to your position specified by the 1st parameter.
In your example you're moving elements of your list to another position in the list (more precisely the end of the list to the beginning).
void list<T,Allocator>::splice ( iterator position, list<T,Allocator>& x, iterator i );
void list<T,Allocator>::splice ( iterator position, list<T,Allocator>& x, iterator start, iterator finish );
It is quite difficult to see just by looking at it, because we have 2 lists and 2 iterators.
The word position
gives it away though. It is stating where to perform the insert
.
The iterator which is i
is what gets moved. In the second overload, the range from start
to finish
but not finish
itself are moved. finish
may be the end of the list.
The position
must belong to the this
list. The iterator must belong to the x
list. Elements are inserted just before position
in the source (this) list and are at the same time removed from the x
list.
Note that cplusplus.com states that the iterators become invalidated once spliced however this is not actually the case, they do remain valid.
cplusplus.com is correct in that the position
may not be one of the spliced elements (in the case that the lists are the same)
In your example:
mylist1.splice ( mylist1.begin(), mylist1, it, mylist1.end());
it
must be an iterator within mylist1. It would appear it must not be mylist1.begin()
.
Your operation moves all the elements from it
onward to the beginning of the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With