1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
|
#include <algorithm>
/*
template <typename Iterator>
struct iterator_types
{
using pointer = Iterator::pointer;
using reference = Iterator::reference;
};
*/
template <typename T>
struct iterator_types //<T *>
{
using pointer = T *;
using reference = T &;
};
template <typename Iterator>
class reverse_iter
{
public:
using pointer = iterator_types<Iterator>::pointer;
using reference = iterator_types<Iterator>::reference;
explicit reverse_iter(Iterator x)
:
current(x)
{}
reference operator*() const
{
Iterator tmp = current;
return (*--tmp);
}
pointer operator->() const
{
return &(operator*());
}
reverse_iter<Iterator>& operator++()
{
--current;
return (*this);
}
reverse_iter<Iterator> operator++(int)
{
reverse_iter<Iterator> tmp(current--);
return (tmp);
}
bool operator!=(reverse_iter<Iterator> const &other)
{
return (current != other.current);
}
private:
Iterator current;
};
template <typename Type>
class Vector
{
using iterator = Type *;
using reverse_iterator = reverse_iter<iterator>;
public:
Vector()
{
init(0);
};
Vector(size_t n)
{
init(n);
}
Vector(Vector<Type> const &other)
{
construct(other);
}
~Vector()
{
delete[] start;
}
Vector<Type> const &operator=(Vector<Type> const &other)
{
if (this != &other)
{
delete[] start;
construct(other);
}
return (*this);
}
Type &operator[](size_t index)
{
if (index > (finish - start))
throw "Vector array index out of bounds";
return (start[index]);
}
Vector<Type> &sort()
{
::sort(start, finish);
return (*this);
}
void push_back(Type const &value)
{
if (!finish)
init(1);
else if (finish == end_of_storage)
{
Vector<Type>
enlarged((end_of_storage - start) << 1);
copy(start, finish, enlarged.start);
delete[] start;
finish = enlarged.start + (finish - start);
start = enlarged.start;
end_of_storage = enlarged.end_of_storage;
enlarged.start = 0;
}
*finish++ = value;
}
iterator begin()
{
return (start);
}
iterator end()
{
return (finish);
}
reverse_iterator rbegin()
{
return (reverse_iterator(finish));
}
reverse_iterator rend()
{
return (reverse_iterator(start));
}
size_t size()
{
return (finish - start);
}
private:
void init(size_t n)
{
if (n)
{
start = new Type[n];
finish = start + n;
end_of_storage = start + n;
}
else
{
start = 0;
finish = 0;
end_of_storage = 0;
}
}
void construct(Vector<Type> const &other)
{
init(other.finish - other.start);
copy(other.start, other.finish, start);
}
iterator
start,
finish,
end_of_storage;
};
|