fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. typedef std::vector<std::vector<double>> matrix_type;
  6.  
  7. template <typename T> // a handy template to output a vector with <<
  8. std::ostream &operator <<(std::ostream &out, const std::vector<T> &obj)
  9. {
  10. out << "<";
  11. const char *sep = "";
  12. for (auto &item : obj) // for each item in the vector
  13. {
  14. out << sep << item;
  15. sep = ", ";
  16. }
  17. return out << ">";
  18. }
  19.  
  20. int main()
  21. {
  22. matrix_type identity = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
  23. std::cout << "identity = " << identity << "\n\n";
  24.  
  25. matrix_type copy1(identity); // deep copy using constructor
  26. copy1[0][2] = 42;
  27. std::cout << "copy1 = " << copy1 << "\n";
  28. std::cout << "identity = " << identity << "\n\n";
  29.  
  30. matrix_type copy2;
  31. copy2 = identity; // deep copy using assignment operator
  32. copy2[1][0] = 24;
  33. std::cout << "copy2 = " << copy2 << "\n";
  34. std::cout << "copy1 = " << copy1 << "\n";
  35. std::cout << "identity = " << identity << "\n\n";
  36.  
  37. return 0;
  38. }
  39.  
Success #stdin #stdout 0s 4524KB
stdin
Standard input is empty
stdout
identity = <<1, 0, 0>, <0, 1, 0>, <0, 0, 1>>

copy1 = <<1, 0, 42>, <0, 1, 0>, <0, 0, 1>>
identity = <<1, 0, 0>, <0, 1, 0>, <0, 0, 1>>

copy2 = <<1, 0, 0>, <24, 1, 0>, <0, 0, 1>>
copy1 = <<1, 0, 42>, <0, 1, 0>, <0, 0, 1>>
identity = <<1, 0, 0>, <0, 1, 0>, <0, 0, 1>>