将一个列表中的元素添加到另一个列表的简单方法

发布于 2024-10-02 19:20:29 字数 374 浏览 0 评论 0原文

将一个 std::list 中的所有元素添加到另一个 std::list 的“正确”方法是什么?

void
Node::addChilds(const NodeList *list)
{
    for(NodeList::const_iterator i = list->begin();
        i != list->end();
        ++i)
        {
            this->m_childs.push_back(*i);
        }
}

我考虑过 std::copy,但据我所知,对于复制,我必须调整目标列表的大小,备份结束迭代器(调整大小之前)等。

我正在寻找单行语句。

What is the "correct" way to add all elements from one std::list to another one?

void
Node::addChilds(const NodeList *list)
{
    for(NodeList::const_iterator i = list->begin();
        i != list->end();
        ++i)
        {
            this->m_childs.push_back(*i);
        }
}

I thought about std::copy, but afaik for copy I have to resize the destination list, backup the end iterator (before resize) etc.

I'm searching for a single-line statement.

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

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

发布评论

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

评论(4

桃气十足 2024-10-09 19:20:29
this->m_childs.insert(this->m_childs.end(), list->begin(), list->end());
this->m_childs.insert(this->m_childs.end(), list->begin(), list->end());
哭了丶谁疼 2024-10-09 19:20:29

使用 back_insert_iterator。如果 std::listm_childs 的类型,

std::copy(list.begin(), list.end(),
          std::back_insert_iterator<std::list<T> >(m_childs));

Use a back_insert_iterator. If std::list<T> is the type of m_childs,

std::copy(list.begin(), list.end(),
          std::back_insert_iterator<std::list<T> >(m_childs));
禾厶谷欠 2024-10-09 19:20:29

如果要移动元素,可以使用拼接。否则复制它们,如 ybungalobill 或 larsmans 所解释的。

If the elements should be moved, you can use splice. Otherwise copy them, as explained by ybungalobill or larsmans.

有木有妳兜一样 2024-10-09 19:20:29

Scott Meyers 在第 5 项的“有效 STL”中讨论了这个特定主题(并在第 4 项中提到了拼接)。他更喜欢 ybungalobill 的版本,但主要是因为他认为代码更干净、更清晰,因为它强调“插入”一词,而不是“复制”一词。

几乎所有使用迭代器的 std::copy 的使用(例如 back_inserter)都可以替换为对范围成员函数的调用(例如 .insert(position, begin) ,结束))。

splice 是一个常量时间成员函数,因此如果适用于这种特定情况,它会更快。

Scott Meyers writes about this specific subject in "Effective STL", in item 5 (and mentions splice in item 4). He prefers ybungalobill's version, but mostly because he thinks the code is cleaner and clearer since it emphasizes the word 'insert' and not the word 'copy'.

Almost all uses of std::copy which uses a iterator (like back_inserter) can be replaced with calls to range member functions (like .insert(position, begin, end)).

splice is a constant-time member function, so it will be faster if it is applicable in this specific case.

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