CSCI 330 Lab: Vector

Complete the implementation of the my_vector template class as defined below so that it runs correctly with the test code test_my_vector.cpp given below.

#ifndef MY_VECTOR_H
#define MY_VECTOR_H

// my_vector.h

using namespace std;

template <class T>  
class my_vector
{
public:
   typedef T * iterator;
   typedef T value_type; // type of elements in container

   // constructors
   my_vector(); // no argument constructor
   my_vector(unsigned int size);
   my_vector(unsigned int size, const T & initial);
   my_vector(const my_vector & v); // copy constructor
   ~my_vector(); // destructor


   // member functions
   int capacity() const; // return capacity of vector (in elements)
   unsigned int size() const; // return the number of elements in the vector
   bool empty() const; // return true if vector has no elements

   iterator begin(); // return an iterator pointing to the first element
   iterator end(); // return an iterator pointing to one past the last element
   T & front(); // return a reference to the first element
   T & back(); // return a reference to the last element
   void push_back(const T & value); // add a new element
   void pop_back(); // remove the last element

   void reserve(unsigned int new_capacity); // adjust capacity
   void resize(unsigned int new_size); // adjust size

   // operators
   T & operator [ ](unsigned int index); // return reference to numbered element

private:
   unsigned int my_size;
   unsigned int my_capacity;
   T * buffer;
};

#endif



// test_my_vector.cpp

#include <iostream>
#include <vector>
#include <string>
#include <cassert>
#include "my_vector.h"

using namespace std;

int main(char* args[])
{
   //#define VECTOR vector
   #define VECTOR my_vector

   VECTOR<int> v;

   v.reserve(2);
   assert(v.capacity() == 2);

   VECTOR<string> v1(2);
   assert(v1.capacity() == 2);
   assert(v1.size() == 2);
   assert(v1[0] == "");
   assert(v1[1] == "");

   v1[0] = "hi";
   assert(v1[0] == "hi");

   VECTOR<int> v2(2, 7);
   assert(v2[1] == 7);

   VECTOR<string> v3(2, "hello");
   assert(v3.size() == 2);
   assert(v3.capacity() == 2);
   assert(v3[0] == "hello");
   assert(v3[1] == "hello");

   v3.resize(1);
   assert(v3.size() == 1);
   assert(v3[0] == "hello");

   VECTOR<string> v4 = v3;
   assert(v4.size() == 1);
   assert(v4[0] == v3[0]);
   v3[0] = "test";
   assert(v4[0] != v3[0]);  // fails when assignment results in shallow copy
   assert(v4[0] == "hello");

   v3.pop_back();
   assert(v3.size() == 0);

   VECTOR<int> v5(7, 9);
   VECTOR<int>::iterator it = v5.begin();
   while (it != v5.end())
   {
      assert(*it == 9);
      ++it;
   }

   VECTOR<int> v6;
   v6.push_back(100);
   assert(v6.size() == 1);
   assert(v6[0] == 100);
   v6.push_back(101);
   assert(v6.size() == 2);
   assert(v6[0] == 100);
   assert(v6[1] == 101);

   cout << "OK\n";
   cin.get();
}