开发者

Join and re-split two std::list's without allocation

开发者 https://www.devze.com 2023-04-11 20:58 出处:网络
I would like to do the following: join two std::lists (l1 and l2) pass the combined list to a function restore the two or开发者_StackOverflow社区iginal lists

I would like to do the following:

  1. join two std::lists (l1 and l2)
  2. pass the combined list to a function
  3. 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号