Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Linked list behavior

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.

like image 675
Gokul Avatar asked Feb 27 '10 21:02

Gokul


2 Answers

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

like image 119
Arun Avatar answered Oct 13 '22 19:10

Arun


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.

like image 24
Tronic Avatar answered Oct 13 '22 19:10

Tronic