// -*- coding: utf-8 -*- // Time-stamp: // Classe pour des tableaux extensibles génériques. #ifndef VECTOR_H #define VECTOR_H #include using namespace std; template class Vector { public: // Constructor with an initial capacity Vector(int n = 1) : capacity(n), size(0) { // Allocate the array alloc(); } // Copy constructor Vector(const Vector& v) : capacity(v.size), size(v.size) { // Allocate the array alloc(); // Copy the elements copy(v.p); } // Assigment operator Vector& operator=(const Vector& v) { // Free the array free(); // New capacity and size capacity = size = v.size; // Allocate the array alloc(); // Copy the elements copy(v.p); // Return it return *this; } // Test if empty bool empty() { return size == 0; } // Access operators // Access to a non constant vector T& operator[](int n) { if (0 <= n && n < size) return p[n]; else throw exception(); } // Access to a non constant vector const T& operator[](int n) const { if (0 <= n && n < size) return p[n]; else throw exception(); } // Add a new element void put(const T& a) { if (size == capacity) { // Temporary for the array T* q = p; // Double capacity capacity *= 2; // Allocate a new array alloc(); // Copy the elements copy(q); // Free old array delete [] q; } // Copy the new element and increment size p[size++] = a; } // Remove the last element void pop() { if (size > 0) --size; else throw exception(); } // Get the last element T get() { if (size > 0) return p[size-1]; else throw exception(); } // Iterator type typedef T* iterator; iterator begin() { return p; } iterator end() { return p+size; } int getSize() { return size; } // Destructor ~Vector() { free(); } private: // Allocation du tableau // + capacity doit être valable void alloc() { p = new T[capacity]; } // Libération du tableau void free() { if (p != 0) delete [] p; } // Initialisation du tableau à partir d'un autre tableau // + nlin et ncol doivent être valables // + Le tableau doit être alloué void copy(T* source) { // Copie des valeurs for(int i = 0; i < size; i++) p[i] = source[i]; } T *p; // Pointer to the array int capacity; // Size of the array int size; // Number of elements in the array }; #endif