Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to add elements from one list to another list

Tags:

c++

stl

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.

like image 796
cytrinox Avatar asked Nov 18 '10 16:11

cytrinox


People also ask

How do you add an element from a list to another list?

You can use the extend() method to add another list to a list, i.e., combine lists. All items are added to the end of the original list. You may specify other iterable objects, such as tuple . In the case of a string ( str ), each character is added one by one.

How do I add content from one list to another in Python?

To append elements from another list to the current list, use the extend() method.

How do you append a list to another list in Java?

Use addAll () method to concatenate the given list1 and list2 into the newly created list.


2 Answers

this->m_childs.insert(this->m_childs.end(), list->begin(), list->end());
like image 184
Yakov Galka Avatar answered Sep 28 '22 07:09

Yakov Galka


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));
like image 29
Fred Foo Avatar answered Sep 28 '22 08:09

Fred Foo