Deepcopy: Difference between revisions

1,380 bytes added ,  3 years ago
Added C++ implementation
No edit summary
(Added C++ implementation)
Line 310:
}
}</lang>
 
=={{header|C++}}==
 
In C++ a type defines its own copy semantics. The standard containers copy all of their elements by value
including elements that are complex or are themselves containers. However if the container contains pointers, the
pointers themselves are copied and will continue to point to the original elements. The example below does not use
any pointers.
 
<lang cpp>
#include <array>
#include <iostream>
#include <list>
#include <map>
#include <vector>
 
int main()
{
// make a nested structure to copy - a map of arrays containing vectors of strings
auto myNumbers = std::vector<std::string>{"one", "two", "three", "four"};
auto myColors = std::vector<std::string>{"red", "green", "blue"};
auto myArray = std::array<std::vector<std::string>, 2>{myNumbers, myColors};
auto myMap = std::map<int, decltype(myArray)> {{3, myArray}, {7, myArray}};
 
// make a deep copy of the map
auto mapCopy = myMap;
 
// modify the copy
mapCopy[3][0][1] = "2";
mapCopy[7][1][2] = "purple";
std::cout << "the original values:\n";
std::cout << myMap[3][0][1] << "\n";
std::cout << myMap[7][1][2] << "\n\n";
 
std::cout << "the modified copy:\n";
std::cout << mapCopy[3][0][1] << "\n";
std::cout << mapCopy[7][1][2] << "\n";
}</lang>
{{out}}
<pre>the original values:
two
blue
 
the modified copy:
2
purple
</pre>
 
=={{header|Common Lisp}}==
125

edits