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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:01:09  来源:igfitidea点击:

how to append a list<T> object to another

c++liststl

提问by BCS

in C++, I have two list<T>objects Aand Band I want to add all the members of Bto 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>对象AB我想将 的所有成员添加BA. 我搜索了几个不同的来源,但没有找到一个简单的解决方案 (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 ); }