Advertisement
Guest User

Untitled

a guest
Nov 13th, 2019
657
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. //eMail: francescodero@outlook.it
  2.  
  3. #pragma once
  4. #include <cstdlib>
  5.  
  6. namespace dero
  7. {
  8.     template <class t>
  9.     class vector
  10.     {
  11.         protected:
  12.             int size;
  13.             int capacity;
  14.             t * storage;
  15.  
  16.         public:
  17.             vector();
  18.             ~vector();
  19.             void append(const t & elem);
  20.             t& operator [] (int index);
  21.     };
  22. }
  23.  
  24. template <class t> dero::vector<t>::vector()
  25. // dero::vector default constructor
  26. // -> want no parameters
  27. // <- initializes the vector correctly
  28. {
  29.     size = 0;
  30.     capacity = 1;
  31.     storage = (int*)malloc(sizeof(t));
  32. };
  33.  
  34. template <class t> dero::vector<t>::~vector()
  35. // dero::vector default destructor
  36. // -> want no parameters
  37. // <- destroy the storage
  38. {
  39.     size = 0;
  40.     capacity = 1;
  41.     delete [] storage;
  42. };
  43.  
  44. template <class t> void dero::vector<t>::append(const t & elem)
  45. // dero::vector primary insertion method
  46. // -> want the element to append
  47. // <- append the element
  48. {
  49.     size++;
  50.     if ( capacity >= size )
  51.         storage[(size-1)] = elem;
  52.     else
  53.     {
  54.         capacity *= 2;
  55.         auto x = realloc(storage,capacity*sizeof(t));
  56.         storage[(size-1)] = elem;
  57.     }
  58. };
  59.  
  60. template <class t> t& dero::vector<t>::operator [] (int index)
  61. // dero::vector access operator
  62. // -> want the index
  63. // <- return a reference to the element in that position
  64. {
  65.     return storage[index];
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement