9

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.

cytrinox
  • 1,846
  • 5
  • 25
  • 46

4 Answers4

13
this->m_childs.insert(this->m_childs.end(), list->begin(), list->end());
Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
12

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));
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • both this and @ybungalobill are correct. I prefer this however. Here's why: [http://stackoverflow.com/questions/4152815/stl-use-member-functions-or-functions-in-algorithm/4156380#4156380] – John Dibling Nov 18 '10 at 16:32
  • 3
    I would have thought member function `list::insert` would be more efficient. Any idea whether that's right? – Steve Townsend Nov 18 '10 at 16:34
  • 2
    On Linux/x86 running on an Intel Core2 @1.86GHz, GCC 4.3.2, filling a list with 10000000 elements, copying that to another list and printing the second element takes ca. 2.5s wall-clock time, 2.1s user time, independent of whether `copy` or `insert` is used. – Fred Foo Nov 18 '10 at 16:54
12

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

SebastianK
  • 3,582
  • 3
  • 30
  • 48
3

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.

AzP
  • 1,081
  • 1
  • 16
  • 27