I would like to do the following:
- join two
std::list
s (l1
andl2
) - pass the combined list to a function
- restore the two original lists
All this should happen without allocating new memory.
First I wanted to try this with splice()
, but then I read that the iterators of the moved items would be invalidated by splice()
.
Then, however, I read this SO answer: splice() on std::list and iterator invalidation
and decided to try it anyway:
iterator temp = l2.begin();
l1.splice(l1.end(), l2);
my_function(l1);
l2.splice(l2.end(), l1, temp, l1.end());
This works in many cases, but if l2
is initially empty, it doesn't (because temp
doesn't point to anything meaningful).
Of course I could check for l2.size() > 0
, but all this seems a little too work-around-ish to me.
Does anyone know a better/cleaner solution to my initial problem?