diff --git a/lectures/08_vector_implementation/main.cpp b/lectures/08_vector_implementation/main.cpp new file mode 100644 index 0000000..046fb1b --- /dev/null +++ b/lectures/08_vector_implementation/main.cpp @@ -0,0 +1,88 @@ +#include +//#include + +#include "vec.h" + +int main(){ + + // Vec is a template, not a type. + Vec teams; + teams.push_back("rpi"); + teams.push_back("wpi"); + teams.push_back("yale"); + teams.push_back("brown"); + teams.push_back("cornell"); + teams.push_back("colgate"); + teams.push_back("miami"); + teams.push_back("colorado"); + teams.push_back("harvard"); + + // we can use a type alias defined inside a class even if there is no object of that class. The type alias becomes part of the class's scope and can be used anywhere in your code where the class's scope is visible. although no object of Vec is created in this code, the type alias size_type is still accessible because it is part of the class's scope. + for(Vec::size_type i = 0; i < teams.size(); i++){ + std::cout << teams[i] << std::endl; + } + std::cout<<"========="<::size_type i = 0; i < teams.size(); i++){ + std::cout << teams[i] << std::endl; + } + std::cout<<"========="<::size_type i = 0; i < teams.size(); i++){ + std::cout << teams[i] << std::endl; + } + std::cout<<"========="< v(4, 0.0); + v[0] = 13.1; v[2] = 3.14; + // copy a vector - calls copy constructor. + Vec u(v); + u[2] = 6.5; + u[3] = -4.8; + for (unsigned int i = 0; i < v.size(); ++i){ + std::cout << "u[" << i << "] is " << u[i] << " and v[" << i << "] is " << v[i] << std::endl; + } + std::cout<<"========="< w(v), w is a copy of the elements in v. + // we use the const keyword in front of a variable definition to indicate that the value of the variable cannot be changed after it is initialized. + const Vec w = v; + for (unsigned int i = 0; i < v.size(); ++i){ + std::cout << "w[" << i << "] is " << w[i] << " and v[" << i << "] is " << v[i] << std::endl; + } + std::cout<<"========="< y; + y = v; + for (unsigned int i = 0; i < v.size(); ++i){ + std::cout << "y[" << i << "] is " << y[i] << " and v[" << i << "] is " << v[i] << std::endl; + } + std::cout<<"========="< +class Vec{ +public: + typedef unsigned int size_type; + Vec(){ + m_data = new T[2]; + m_size = 0; + capacity = 2; + } + 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; + T* temp = new T[capacity]; + for(unsigned int i=0;i