C++链表行为

发布于 2024-08-23 14:05:48 字数 129 浏览 3 评论 0原文

我有一些 C 代码,其中有两个链接列表(比如 A 和 B),A 被插入到 B 的特定位置,并且 A 仍然有元素。

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

谢谢, 戈库尔。

I have some C code, where in there are two linked lists(say A and B) and A is inserted at a particular position into B and A still has elements.

How do I simulate the same behavior effectively using the C++ STL? If I try splice, it makes the second one empty.

Thanks,
Gokul.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

只等公子 2024-08-30 14:05:48

尝试 insert:

B.insert( position, A.begin(), A.end() );

在“位置”之前插入 A 元素的副本到 B 中。 A 本身保持不变。请参阅此链接

Try insert:

B.insert( position, A.begin(), A.end() );

to insert copies of the elements of A in B before 'position'. A itself remains unchanged. See this link

蓝天 2024-08-30 14:05:48

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

std::copy(a.begin(), a.end(), std::inserter(b, b_iterator));

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

You need to copy the elements. Consider something like this:

std::copy(a.begin(), a.end(), std::inserter(b, b_iterator));

If you want the same nodes shared by two lists, this is simply not supported by std::list (STL containers always have exclusive ownership). You can avoid duplicating the elements by storing pointers in the list, or by using boost::ptr_list, which internally stores pointers but offers a nicer API.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文