To deep copy a std::list in C++, you can use the list's copy constructor or the std::copy algorithm to create a new list with the same elements.
In this example,
originalList
with integer values.deepCopiedList
with the same elements.#include <iostream>
#include <list>
void printList(const std::list<int>& lst) {
for (int val : lst) {
std::cout << val << " ";
}
std::cout << std::endl;
}
int main() {
std::list<int> originalList = {1, 2, 3, 4, 5};
std::list<int> deepCopiedList = originalList;
std::cout << "Original List: ";
printList(originalList);
std::cout << "Deep Copied List: ";
printList(deepCopiedList);
return 0;
}
Original List: 1 2 3 4 5 Deep Copied List: 1 2 3 4 5
In this example,
Person
with properties name
and age
.originalList
containing Person
objects.Person
object and create a new list named deepCopiedList
with the same elements.#include <iostream>
#include <list>
#include <algorithm>
class Person {
public:
std::string name;
int age;
Person(std::string n, int a) : name(n), age(a) {}
Person(const Person& other) : name(other.name), age(other.age) {}
friend std::ostream& operator<<(std::ostream& os, const Person& p) {
os << "Person(name: " << p.name << ", age: " << p.age << ")";
return os;
}
};
void printList(const std::list<Person>& lst) {
for (const Person& p : lst) {
std::cout << p << " ";
}
std::cout << std::endl;
}
int main() {
std::list<Person> originalList = { Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35) };
std::list<Person> deepCopiedList;
std::copy(originalList.begin(), originalList.end(), std::back_inserter(deepCopiedList));
std::cout << "Original List: ";
printList(originalList);
std::cout << "Deep Copied List: ";
printList(deepCopiedList);
return 0;
}
Original List: Person(name: Alice, age: 30) Person(name: Bob, age: 25) Person(name: Charlie, age: 35) Deep Copied List: Person(name: Alice, age: 30) Person(name: Bob, age: 25) Person(name: Charlie, age: 35)
In this tutorial, we learned How to deep Copy a List in C++ language with well detailed examples.