To join lists in C++ using `std::list`, you can use the `insert` method to combine multiple lists into a single list.
In this example,
list1
and list2
with integer values.joinedList
and use the insert
method to add all elements from list1
and list2
to joinedList
.#include <iostream>
#include <list>
int main() {
std::list<int> list1 = {1, 2, 3};
std::list<int> list2 = {4, 5, 6};
std::list<int> joinedList;
joinedList.insert(joinedList.end(), list1.begin(), list1.end());
joinedList.insert(joinedList.end(), list2.begin(), list2.end());
std::cout << "Joined List: ";
for (int n : joinedList) {
std::cout << n << " ";
}
return 0;
}
Joined List: 1 2 3 4 5 6
In this example,
listA
, listB
, and listC
with string values.resultList
and use the insert
method to add all elements from listA
, listB
, and listC
to resultList
.#include <iostream>
#include <list>
#include <string>
int main() {
std::list<std::string> listA = {"apple", "banana"};
std::list<std::string> listB = {"cherry", "date"};
std::list<std::string> listC = {"fig", "grape"};
std::list<std::string> resultList;
resultList.insert(resultList.end(), listA.begin(), listA.end());
resultList.insert(resultList.end(), listB.begin(), listB.end());
resultList.insert(resultList.end(), listC.begin(), listC.end());
std::cout << "Joined List: ";
for (const std::string& s : resultList) {
std::cout << s << " ";
}
return 0;
}
Joined List: apple banana cherry date fig grape
In this tutorial, we learned How to Join Lists in C++ language with well detailed examples.