C++链接列表行为

Gok*_*kul 5 c++ stl linked-list stdlist

我有一些C代码,其中有两个链表(比如A和B),A在特定位置插入B,A仍然有元素.

如何使用C++ STL有效地模拟相同的行为?如果我尝试拼接,它会使第二个空.

谢谢,Gokul.

Aru*_*run 7

尝试插入:

B.insert( position, A.begin(), A.end() );
Run Code Online (Sandbox Code Playgroud)

在"位置"之前插入B中A元素的副本.本身保持不变.看到这个链接


Tro*_*nic 2

您需要复制元素。考虑这样的事情:

std::copy(a.begin(), a.end(), std::inserter(b, b_iterator));
Run Code Online (Sandbox Code Playgroud)

如果您希望两个列表共享相同的节点,则根本不支持std::list(STL 容器始终具有独占所有权)。您可以通过在列表中存储指针或使用 来避免重复元素boost::ptr_list,后者在内部存储指针但提供更好的 API。