Simple way to add elements from one list to another list
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 state开发者_高级运维ment.
this->m_childs.insert(this->m_childs.end(), list->begin(), list->end());
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));
If the elements should be moved, you can use splice. Otherwise copy them, as explained by ybungalobill or larsmans.
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.
精彩评论