连接并重新分割两个 std::list 而不进行分配
我想执行以下操作:
- 加入两个
std::list
(l1
和l2
) - 将组合列表传递给函数
- 恢复两个原始列表
所有这一切都应该在不分配新内存的情况下发生。
首先,我想使用 splice() 尝试此操作,但后来我读到,已移动项目的迭代器将被 splice() 无效。 然而,然后,我读到了这个答案: std 上的 splice() : :列表和迭代器失效 并决定无论如何尝试一下:
iterator temp = l2.begin();
l1.splice(l1.end(), l2);
my_function(l1);
l2.splice(l2.end(), l1, temp, l1.end());
这在很多情况下都有效,但如果 l2
最初为空,则不会(因为 temp
没有指向任何有意义的东西)。
当然我可以检查 l2.size() > 0
,但这一切对我来说似乎有点过于解决问题。
有谁知道我最初的问题有更好/更干净的解决方案吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以扭转逻辑以保留有效的迭代器:
You could turn the logic around to keep a valid iterator: