// An implementation of a simplified STL Vector // George F. Riley, Georgia Tech, Fall 2009 template class GFRVec { public: GFRVec() : first(0), last(0), end(0) {} GFRVec(size_t n) { // Create a GFRVec with "n" copies of T, with default constructor first = new T[n]; last = first + n; end = last; } GFRVec(size_t n, const T& t) { // Create a GFRVec with "n" copies of t first = new T[n]; for (size_t i = 0; i < n; ++i) first[i] = t; // Populate the vector last = first + n; end = last; } GFRVec(const GFRVec& c) { // Copy Constructor first = new T[c.size()]; // Allocate memory for (size_t i = 0; i < c.size(); ++i) first[i] = c[i]; // Copy elements last = first + c.size(); end = last; } ~GFRVec() { // Destructor, remove all elements clear(); } GFRVec& operator=(const GFRVec& rhs) { // Assignment operator if (this == &rhs) return *this; // Self assignment delete [] first; // Free old memory first = new T[rhs.size()]; // Allocate memory for (size_t i = 0; i < rhs.size(); ++i) first[i] = rhs[i]; // Copy the elements last = first + rhs.size(); end = last; } T& operator[](size_t i) const { // Indexing operator return first[i]; } T& back() const { // Return last element return first[size()-1]; } T& front() const { // Return last element return first[0]; } void pop_back() { // Remove last element last--; first[size()].~T(); // Call destructor on just popped object } void push_back(const T& t) { // Add new element if (last != end) { // Room for new object without re-allocating first[size()] = t; last++; } else { // Need to re-allocate T* tmp = new T[end-first+1]; for (size_t i = 0; i < size(); ++i) tmp[i] = first[i]; tmp[size()] = t; // Add new element last = tmp + (last - first) + 1; end = last; delete [] first; // Delete and destroy old objects first = tmp; } } size_t size() const { // Number of elements in the vector return last - first; } void reserve(size_t n) { // Reserve space for "n" elements if (n <= (end-first)) return; // Less than already reserved T* tmp = new T[n]; // Allocate new memory for (size_t i = 0; i < size(); ++i) tmp[i] = first[i]; last = tmp + last - first; delete [] first; first = tmp; end = first + n; } void clear() { // Erase all elements while(size()) pop_back(); } private: T* first; // Initial element T* last; // Last element T* end; // End of allocated storage };