I would like to do the following:
- join two
std::lists (l1andl2) - pass the combined list to a function
- restore the two or开发者_StackOverflow社区iginal 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?
You could turn the logic around to keep a valid iterator:
auto temp = l2.begin();
l2.splice(temp, l1); // "L2 = L1 + L2"
my_function(l2);
l1.splice(l1.end(), l2, l2.begin(), temp); // restores both l1 and l2
加载中,请稍侯......
精彩评论