C++ 如何将 list<T> 对象附加到另一个对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1449703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to append a list<T> object to another
提问by BCS
in C++, I have two list<T>
objects A
and B
and I want to add all the members of B
to the end of A
. I've searched a few different sources and haven't found a simple solution (e.i. A.append(B);
) and this surprises me a bit.
在 C++ 中,我有两个list<T>
对象A
,B
我想将 的所有成员添加B
到A
. 我搜索了几个不同的来源,但没有找到一个简单的解决方案 (ei A.append(B);
),这让我有点惊讶。
What is the best way to do this?
做这个的最好方式是什么?
As it happens, I don't care about B after this (it gets deleted in the very next line) so if there is a way to leverage that for better perf I'm also interested in that.
碰巧的是,在这之后我不关心 B(它在下一行被删除)所以如果有办法利用它来获得更好的性能,我也对此感兴趣。
回答by UncleBens
If you want to append copies of itemsin B, you can do:
如果要在 B 中附加项目的副本,可以执行以下操作:
a.insert(a.end(), b.begin(), b.end());
If you want to move itemsof B to the end of A (emptying B at the same time), you can do:
如果要将B 的项目移动到 A 的末尾(同时清空 B),可以执行以下操作:
a.splice(a.end(), b);
In your situation splicing would be better, since it just involves adjusting a couple of pointers in the linked lists.
在你的情况下拼接会更好,因为它只涉及调整链表中的几个指针。
回答by serup
one example using boost
一个使用 boost 的例子
std::list<T> A; // object A is a list containing T structure
std::list<T> B; // object B is a list containing T structure
// append list B to list A
BOOST_FOREACH(auto &listElement, B) { A.push_back( listElement ); }