how to append a list<T> object to another

C++ListStl

C++ Problem Overview


in C++, I have two list<T> objects A and B and I want to add all the members of B to the end of A. I've searched a few different sources and haven't found a simple solution (e.i. A.append(B);) and this surprises me a bit.

What is the best way to do this?

As it happens, I don't care about B after this (it gets deleted in the very next line) so if there is a way to leverage that for better perf I'm also interested in that.

C++ Solutions


Solution 1 - C++

If you want to append copies of items in B, you can do:

a.insert(a.end(), b.begin(), b.end());

If you want to move items of B to the end of A (emptying B at the same time), you can do:

a.splice(a.end(), b);

In your situation splicing would be better, since it just involves adjusting a couple of pointers in the linked lists.

Solution 2 - C++

one example using boost

std::list<T> A; // object A is a list containing T structure
std::list<T> B; // object B is a list containing T structure

// append list B to list A
BOOST_FOREACH(auto &listElement, B) { A.push_back( listElement ); }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBCSView Question on Stackoverflow
Solution 1 - C++UncleBensView Answer on Stackoverflow
Solution 2 - C++serupView Answer on Stackoverflow