To append a list to another list in C++ using std::list
, you can use the insert
function or the splice
function.
In this example,
and
.list1
and list2
with initial values.insert
function to insert all elements of list2
at the end of list1
.list1
to standard output.#include <iostream>
#include <list>
int main() {
std::list<int> list1 = {1, 2, 3};
std::list<int> list2 = {4, 5, 6};
list1.insert(list1.end(), list2.begin(), list2.end());
for (int num : list1) {
std::cout << num << " ";
}
return 0;
}
1 2 3 4 5 6
In this example,
and
.list1
and list2
with initial values.splice
function to transfer all elements of list2
to the end of list1
.list1
to standard output.#include <iostream>
#include <list>
int main() {
std::list<int> list1 = {1, 2, 3};
std::list<int> list2 = {4, 5, 6};
list1.splice(list1.end(), list2);
for (int num : list1) {
std::cout << num << " ";
}
return 0;
}
1 2 3 4 5 6
In this tutorial, we learned How to Append a List to another List in C++ language with well detailed examples.