Saikiran
Saikiran

Reputation: 151

Functioning of splice() in cpp

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());

Upvotes: 7

Views: 5806

Answers (4)

CashCow
CashCow

Reputation: 31435

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.

Upvotes: 1

Andreas Brinck
Andreas Brinck

Reputation: 52519

The reason you need to supply the source list is that otherwise the elements can't be removed from it.

Upvotes: 4

SirDarius
SirDarius

Reputation: 42889

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.

Upvotes: 5

Uflex
Uflex

Reputation: 1426

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).

Upvotes: 1

Related Questions