5

I have some C code, where in there are two linked lists(say A and B) and A is inserted at a particular position into B and A still has elements.

How do I simulate the same behavior effectively using the C++ STL? If I try splice, it makes the second one empty.

Thanks, Gokul.

Peter Alexander
  • 53,344
  • 14
  • 119
  • 168
Gokul
  • 893
  • 11
  • 27

2 Answers2

7

Try insert:

B.insert( position, A.begin(), A.end() );

to insert copies of the elements of A in B before 'position'. A itself remains unchanged. See this link

Arun
  • 19,750
  • 10
  • 51
  • 60
2

You need to copy the elements. Consider something like this:

std::copy(a.begin(), a.end(), std::inserter(b, b_iterator));

If you want the same nodes shared by two lists, this is simply not supported by std::list (STL containers always have exclusive ownership). You can avoid duplicating the elements by storing pointers in the list, or by using boost::ptr_list, which internally stores pointers but offers a nicer API.

Tronic
  • 10,250
  • 2
  • 41
  • 53
  • Note that is is potentially slower than the other solution (http://stackoverflow.com/questions/2349098/2349119#2349119). See the comments at http://stackoverflow.com/questions/2551775/2551808#2551808 for why that is. – sbi Apr 01 '10 at 17:06