adding the shallow copy example
This commit is contained in:
14
lectures/08_vector_implementation/copy.cpp
Normal file
14
lectures/08_vector_implementation/copy.cpp
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
#include <iostream>
|
||||||
|
#include "vec_shallow_copy.h"
|
||||||
|
|
||||||
|
int main(){
|
||||||
|
|
||||||
|
Vec<double> v(4, 0.0);
|
||||||
|
v[0] = 13.1; v[2] = 3.14;
|
||||||
|
Vec<double> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
79
lectures/08_vector_implementation/vec_shallow_copy.h
Normal file
79
lectures/08_vector_implementation/vec_shallow_copy.h
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
template<class T>
|
||||||
|
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<size;i++){
|
||||||
|
m_data[i] = val;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// copy constructor
|
||||||
|
/*Vec(const Vec& other){
|
||||||
|
capacity = other.capacity;
|
||||||
|
m_size = other.m_size;
|
||||||
|
m_data = new T[capacity];
|
||||||
|
for(unsigned int i=0;i<m_size;i++){
|
||||||
|
m_data[i] = other.m_data[i];
|
||||||
|
}
|
||||||
|
}*/
|
||||||
|
|
||||||
|
// destructor
|
||||||
|
~Vec(){
|
||||||
|
delete [] m_data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// assignment operator
|
||||||
|
Vec<T>& 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<m_size;i++){
|
||||||
|
m_data[i] = other.m_data[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
// [] operator
|
||||||
|
T& operator[](int i){
|
||||||
|
return m_data[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned int size(){
|
||||||
|
return m_size;
|
||||||
|
}
|
||||||
|
|
||||||
|
void push_back(const T& val){
|
||||||
|
if(m_size >= 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<m_size;i++){
|
||||||
|
temp[i] = m_data[i];
|
||||||
|
}
|
||||||
|
delete [] m_data;
|
||||||
|
m_data = temp;
|
||||||
|
}
|
||||||
|
m_data[m_size] = val;
|
||||||
|
m_size++;
|
||||||
|
}
|
||||||
|
void pop_back(){
|
||||||
|
m_size--;
|
||||||
|
}
|
||||||
|
private:
|
||||||
|
int capacity;
|
||||||
|
int m_size;
|
||||||
|
T* m_data;
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user