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.
Insert(), and List. InsertRange() methods are used to add and insert items to a List<T>. List<T> is a generic class.
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.
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.
Use the AddRange() method to append a second list to an existing list. list1. AddRange(list2);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With