3

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?

Aswin Prasad
  • 407
  • 6
  • 14
  • Take a look at [Javascript - insert an array inside another array](http://stackoverflow.com/questions/7032550/javascript-insert-an-array-inside-another-array) – Khalil Khalaf Aug 02 '16 at 14:06

2 Answers2

3

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.

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • You didn't mention anything about modifying the original list. – Aswin Prasad Aug 02 '16 at 14:15
  • That used to be true, but since idiots forced the standard to maintain constant-time `size()` for lists, splice is O(n). – Zan Lynx Aug 02 '16 at 15:05
  • @ZanLynx: `this->size += other.size()`, what's the problem? How does a requirement for constant-time size make it impossible to splice in constant time? – Armen Tsirunyan Aug 02 '16 at 15:17
  • @ArmenTsirunyan splicing a subset of a list requires iterating through it to see how much to alter the source & destination lists sizes by – nate Aug 02 '16 at 18:42
3

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.

nate
  • 1,771
  • 12
  • 17