Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to append a list<T> object to another

Tags:

c++

list

stl

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.

like image 462
BCS Avatar asked Sep 19 '09 22:09

BCS


People also ask

What method can you use to put an item into a list T collection?

Insert(), and List. InsertRange() methods are used to add and insert items to a List<T>. List<T> is a generic class.

How do you add an object to a list?

You insert elements (objects) into a Java List using its add() method. Here is an example of adding elements to a Java List using the add() method: List<String> listA = new ArrayList<>(); listA. add("element 1"); listA.

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

Python's append() function inserts a single element into an existing list. The element will be added to the end of the old list rather than being returned to a new list. Adds its argument as a single element to the end of a list. The length of the list increases by one.

Can you add a list to another list C#?

Use the AddRange() method to append a second list to an existing list. list1. AddRange(list2);


1 Answers

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.

like image 185
UncleBens Avatar answered Sep 24 '22 08:09

UncleBens