From 8d54d8c7df9a52c91a28f787bc5832e566a1312f Mon Sep 17 00:00:00 2001 From: Jidong Xiao Date: Tue, 6 Feb 2024 00:43:39 -0500 Subject: [PATCH] adding the shallow copy example --- lectures/08_vector_implementation/copy.cpp | 14 ++++ .../vec_shallow_copy.h | 79 +++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 lectures/08_vector_implementation/copy.cpp create mode 100644 lectures/08_vector_implementation/vec_shallow_copy.h diff --git a/lectures/08_vector_implementation/copy.cpp b/lectures/08_vector_implementation/copy.cpp new file mode 100644 index 0000000..a0f635f --- /dev/null +++ b/lectures/08_vector_implementation/copy.cpp @@ -0,0 +1,14 @@ +#include +#include "vec_shallow_copy.h" + +int main(){ + + Vec v(4, 0.0); + v[0] = 13.1; v[2] = 3.14; + Vec u(v); + u[2] = 6.5; + u[3] = -4.8; + for (unsigned int i=0; i<4; ++i){ + std::cout << u[i] << " " << v[i] << std::endl; + } +} diff --git a/lectures/08_vector_implementation/vec_shallow_copy.h b/lectures/08_vector_implementation/vec_shallow_copy.h new file mode 100644 index 0000000..921063c --- /dev/null +++ b/lectures/08_vector_implementation/vec_shallow_copy.h @@ -0,0 +1,79 @@ +template +class Vec{ +public: + // default constructor + Vec(){ + m_data = new T[2]; + m_size = 0; + capacity = 2; + } + + // other constructor + Vec(int size, const T& val){ + m_data = new T[size]; + m_size = size; + capacity = size; + for(int i=0;i& operator=(const Vec& other){ + if(this != &other){ + capacity = other.capacity; + m_size = other.m_size; + m_data = new T[m_size]; + for(unsigned int i=0;i= capacity){ + capacity = capacity * 2; + // allocate memory for the new array and move content of m_data to the new array. + T* temp = new T[capacity]; + for(unsigned int i=0;i