In C++ using std::list, you can copy a list by initializing a new list with the elements of the original list or by using the assign() method.
In this example,
originalList
using std::list with some elements.copiedList
and initialize it with the elements of originalList
.copiedList
contains all elements of originalList
.#include <iostream>
#include <list>
int main() {
std::list<int> originalList = {1, 2, 3, 4};
std::list<int> copiedList(originalList.begin(), originalList.end());
for (auto const& elem : originalList) {
std::cout << elem << ' ';
}
std::cout << '\n';
for (auto const& elem : copiedList) {
std::cout << elem << ' ';
}
std::cout << '\n';
return 0;
}
1 2 3 4 1 2 3 4
In this example,
originalList
using std::list with some elements.copiedList
.assign()
method of copiedList
and pass the range of originalList
to copy its elements.copiedList
contains all elements of originalList
.#include <iostream>
#include <list>
int main() {
std::list<int> originalList = {1, 2, 3, 4};
std::list<int> copiedList;
copiedList.assign(originalList.begin(), originalList.end());
for (auto const& elem : originalList) {
std::cout << elem << ' ';
}
std::cout << '\n';
for (auto const& elem : copiedList) {
std::cout << elem << ' ';
}
std::cout << '\n';
return 0;
}
1 2 3 4 1 2 3 4
In this tutorial, we learned How to Copy a List in C++ language with well detailed examples.