112

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.

2 Answers 2

224

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.

7
  • 8
    +1. So right. If it could have been so easy and efficient to "slice" maps and sets...
    – paercebal
    Commented Sep 19, 2009 at 23:28
  • Are either of these operations O(1)? Commented Mar 12, 2013 at 20:46
  • 2
    I guess splice should be O(1) for the case above.
    – chunkyguy
    Commented Mar 27, 2013 at 10:48
  • 11
    It is O(1) for a.splice(a.end(), b) and a.splice(a.end(), b, it_b_start), but is O(n) for a.splice(a.end(), b, it_b_start, it_b_end). Commented Aug 8, 2013 at 9:10
  • 15
    Why, o why, couldn't STL just support a.append(b)?
    – srking
    Commented Dec 7, 2017 at 21:00
-3

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 ); }
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.