Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between splice and insert

Tags:

c++

list

stl

Recently I came across functions of list container in STL, i saw

list::splice and list::insert

For me it seems that both does the same job of inserting, I can't specifically find a difference, also i can't find the difference anywhere. So what is specifically the difference, and is there anything special to splice?

like image 841
Aswin Prasad Avatar asked Sep 23 '26 10:09

Aswin Prasad


2 Answers

Splice will move items from the source to the destination. Insert will copy them from the source to the destination. Splice is faster, but will modify the source list, whereas insert takes longer but leaves the original list intact.

like image 141
nate Avatar answered Sep 26 '26 08:09

nate


splice will concatenate two lists in O(1) time, without any copying of data. insert involves copying data, and if you want to concatenate two lists using insert, it will take O(N) time, where N is the number of elements in the list you want to append.

Also, splice will modify (actually, empty), the appended list.

like image 35
Armen Tsirunyan Avatar answered Sep 26 '26 08:09

Armen Tsirunyan