将一个列表中的元素添加到另一个列表的简单方法
将一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
back_insert_iterator
。如果std::list
是m_childs
的类型,Use a
back_insert_iterator
. Ifstd::list<T>
is the type ofm_childs
,如果要移动元素,可以使用拼接。否则复制它们,如 ybungalobill 或 larsmans 所解释的。
If the elements should be moved, you can use splice. Otherwise copy them, as explained by ybungalobill or larsmans.
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 (likeback_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.